diff --git a/.deepsource.toml b/.deepsource.toml index 1fc2a332af..a352c02e4c 100644 --- a/.deepsource.toml +++ b/.deepsource.toml @@ -2,14 +2,11 @@ version = 1 exclude_patterns = [ 'examples/**', - + # auto-generated files 'twilio/rest/**', 'twilio/twiml/**', 'tests/integration/**', - - # compat files - 'twilio/compat.py', ] test_patterns = [ 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 03c5f7bd79..628f850c96 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ *.egg *.egg-info dist -build +/build/ eggs parts bin @@ -20,11 +20,12 @@ pip-log.txt # Unit test / coverage reports .coverage .tox +coverage.xml .DS_Store # sphinx build and rst folder -docs/_build +docs/build docs/source/_rst # PyCharm/IntelliJ @@ -36,4 +37,6 @@ docs/source/_rst # 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 b6eaadb8b3..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,40 +0,0 @@ -dist: xenial # required for Python >= 3.7 -language: python -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" - - "3.7" - - "3.8" -services: - - docker -install: - - pip install virtualenv --upgrade - - make install - - make test-install -script: - - make test -deploy: - - provider: script - script: make docker-build && make docker-push - skip_cleanup: true - on: - tags: true - python: "3.6" - - provider: pypi - skip_cleanup: true - user: "__token__" - password: $PYPI_TOKEN - on: - tags: true - python: "3.6" - -notifications: - slack: - if: branch = master - on_pull_requests: false - on_success: never - on_failure: change - rooms: - - secure: hH8HAepfg60pch6GZ/GprMDpcyu7IjXS4eD+lIcG6TIhEIdn0YCO5K1GiFlDtWgiFfnk5tY5Wr40CEv66cJLg2DnI/q7l3O3wDof80mrbX18EOZ4cFg9ZgAAfSij4znbzf4/9ZQvLxA826Nx/yk9D33o1UE6nHF2xVMfb4bRptw= diff --git a/CHANGES.md b/CHANGES.md index 3b212be72b..37c7984d2f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,2341 @@ 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** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2ff355c06e..41cb4474d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,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? @@ -69,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 @@ -106,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**. @@ -133,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. @@ -162,6 +158,5 @@ There exists a separate `requirements.txt` document under `tests` that contains make test-install test ``` -[docs-link]: https://www.twilio.com/docs/libraries/python [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 index 460d512dbe..065eb8d852 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.6 +FROM python:3.7 ENV PYTHONUNBUFFERED 1 @@ -9,5 +9,7 @@ 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 22f0c0c824..e6154b546b 100644 --- a/ISSUE_TEMPLATE.md +++ b/ISSUE_TEMPLATE.md @@ -1,5 +1,9 @@ ### Issue Summary @@ -21,6 +25,6 @@ A summary of the issue and the environment in which it occurs. If suitable, incl ``` ### Technical details: -* twilio-python version: +* twilio-python version: * python version: 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 5dc18c45be..0000000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (C) 2020, 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/MANIFEST.in b/MANIFEST.in index 7e7ea5a3d1..bc75be523a 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ # Include the SSL certificate file in the package distributed by pip recursive-include twilio/conf * -include LICENSE.md +include LICENSE diff --git a/Makefile b/Makefile index 42ecfb4c79..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,21 +10,27 @@ 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 -r tests/requirements.txt @@ -50,15 +56,23 @@ 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:${TRAVIS_TAG} + 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:latest + docker tag twilio/twilio-python twilio/twilio-python:${CURRENT_TAG} docker-push: - echo "${DOCKER_PASSWORD}" | docker login -u "${DOCKER_USERNAME}" --password-stdin - docker push twilio/twilio-python:${TRAVIS_TAG} + docker push twilio/twilio-python:${GITHUB_TAG} docker push twilio/twilio-python:apidefs-${API_DEFINITIONS_SHA} - docker push twilio/twilio-python:latest + docker push twilio/twilio-python:${CURRENT_TAG} diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 215059a96d..8510bbcb42 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -3,7 +3,7 @@ We appreciate the effort for this pull request but before that please make sure Please format the PR title appropriately based on the type of change: [!]: -Where is one of: docs, chore, feat, fix, test. +Where is one of: docs, chore, feat, fix, test, misc. Add a '!' after the type for breaking changes (e.g. feat!: new breaking feature). **All third-party contributors acknowledge that any contributions they provide will be made under the same open-source license that the open-source project is provided under.** @@ -19,13 +19,13 @@ Closes #2 A short description of what this PR does. ### Checklist -- [ ] I acknowledge that all my contributions will be made under the project's license +- [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](CONTRIBUTING.md) and my PR follows them +- [ ] 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 master branch +- [ ] 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 necessary documentation about the functionality in the appropriate .md file +- [ ] 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 bf356150ca..ed277788d1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # twilio-python -[![Build Status](https://secure.travis-ci.org/twilio/twilio-python.png?branch=master)](https://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) @@ -15,57 +15,111 @@ The Python library documentation can be found [here][libdocs]. `twilio-python` uses a modified version of [Semantic Versioning](https://semver.org) for all changes. [See this document](VERSIONS.md) for details. -### Migrating 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 - ### Supported Python Versions This library supports the following Python implementations: -* Python 2.7 -* Python 3.4 -* Python 3.5 -* Python 3.6 -* Python 3.7 -* Python 3.8 +- 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" + +client = Client(account_sid, auth_token) + +message = client.messages.create( + to="+15558675309", + from_="+15017250604", + body="Hello from Python!") + +print(message.sid) +``` + +Save the file as `send_sms.py`. In the terminal, `cd` to the directory containing the file you just saved then run: - python setup.py install +```shell +python3 send_sms.py +``` + +After a brief delay, you will receive the text message on your phone. + +> **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. -You may need to run the above commands with `sudo`. +## 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 +API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) -Getting started with the Twilio API couldn't be easier. Create a -`Client` and you're ready to go. +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) +``` + +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 @@ -76,7 +130,6 @@ 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() @@ -84,14 +137,17 @@ 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/or Edge for the client: +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. + +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: @@ -110,9 +166,9 @@ This will result in the `hostname` transforming from `api.twilio.com` to `api.sy ```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", @@ -120,28 +176,108 @@ 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 = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) -message = client.messages.create(to="+12316851234", from_="+15555555555", - body="Hello there!") +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 + +async def main(): + account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + auth_token = "your_auth_token" + http_client = AsyncTwilioHttpClient() + client = Client(account_sid, auth_token, http_client=http_client) + + message = await client.messages.create_async(to="+12316851234", from_="+15555555555", + body="Hello there!") + +asyncio.run(main()) +``` + +### Enable Debug Logging + +Log the API request and response data to the console: + +```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 = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = Client(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) try: message = client.messages.create(to="+12316851234", from_="+15555555555", @@ -150,8 +286,6 @@ except TwilioRestException as e: print(e) ``` -For more descriptive exception types, please see the [Twilio documentation](https://www.twilio.com/docs/libraries/python/usage-guide#exceptions). - ### Generating TwiML To control phone calls, your application needs to output [TwiML][twiml]. @@ -171,9 +305,9 @@ print(str(r)) Welcome to twilio! ``` -### Using a Custom HTTP Client +### Other advanced examples -To use a custom HTTP client with this helper library, please see the [Twilio documentation](https://www.twilio.com/docs/libraries/python/custom-http-clients-python). +- [Learn how to create your own custom HTTP client](./advanced-examples/custom-http-client.md) ### Docker Image 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/advanced-examples/custom-http-client.md b/advanced-examples/custom-http-client.md new file mode 100644 index 0000000000..b3b5a7d20e --- /dev/null +++ b/advanced-examples/custom-http-client.md @@ -0,0 +1,154 @@ +# Custom HTTP Clients for the Twilio Python Helper Library + +If you are working with the Twilio Python Helper Library, and you need to be able to modify the HTTP requests that the library makes to the Twilio servers, you’re in the right place. The most common reason for altering the HTTP request is to connect and authenticate with an enterprise’s proxy server. We’ll provide sample code that you can use in your app to handle this and other use cases. + +## Connect and authenticate with a proxy server + +To connect to a proxy server that's between your app and Twilio, you need a way to modify the HTTP requests that the Twilio helper library makes on your behalf to the Twilio REST API. + +In Python, the Twilio helper library uses the [requests](https://docs.python-requests.org/en/master/) library under the hood to make the HTTP requests, and this allows you to [provide your own `http_client`](/docs/libraries/reference/twilio-python/{{ twilio-python-version }}/docs/source/\_rst/twilio.http.html#module-twilio.http.http_client) for making API requests. + +So the question becomes: how do we apply this to a typical Twilio REST API request, such as? + +```python +client = Client(account_sid, auth_token) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +``` + +To start, you should understand when and where a `http_client` is created and used. + +The helper library creates a default `http_client` for you whenever you call the `Client` constructor with your Twilio credentials. Here, you have the option of creating your own `http_client`, and passing to the constructor, instead of using the default implementation. + +Here’s an example of sending an SMS message with a custom client: + +```python +import os +from twilio.rest import Client +from custom_client import MyRequestClass + +from dotenv import load_dotenv +load_dotenv() + +# Custom HTTP Class +my_request_client = MyRequestClass() + +client = Client(os.getenv("ACCOUNT_SID"), os.getenv("AUTH_TOKEN"), + http_client=my_request_client) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +print('Message SID: {}'.format(message.sid)) +``` + +## Create your custom TwilioRestClient + +When you take a closer look at the constructor for `HttpClient`, you see that the `http_client` parameter is actually of type `twilio.http.HttpClient`. + +`HttpClient` is an abstraction that allows plugging in any implementation of an HTTP client you want (or even creating a mocking layer for unit testing). + +However, within the helper library, there is an implementation of `twilio.http.HttpClient` called `TwilioHttpClient`. This class wraps the `twilio.http.HttpClient` and provides it to the Twilio helper library to make the necessary HTTP requests. + +## Call Twilio through a proxy server + +Now that we understand how all the components fit together, we can create our own `HttpClient` that can connect through a proxy server. To make this reusable, here’s a class that you can use to create this `HttpClient` whenever you need one. + +```python +import os +from requests import Request, Session, hooks +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response + +class MyRequestClass(TwilioHttpClient): + def __init__(self): + self.response = None + + def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None, + allow_redirects=False): + # Here you can change the URL, headers and other request parameters + kwargs = { + 'method': method.upper(), + 'url': url, + 'params': params, + 'data': data, + 'headers': headers, + 'auth': auth, + } + + session = Session() + request = Request(**kwargs) + + prepped_request = session.prepare_request(request) + session.proxies.update({ + 'http': os.getenv('HTTP_PROXY'), + 'https': os.getenv('HTTPS_PROXY') + }) + response = session.send( + prepped_request, + allow_redirects=allow_redirects, + timeout=timeout, + ) + + return Response(int(response.status_code), response.text) +``` + +In this example, we are using some environment variables loaded at the program startup to retrieve various configuration settings: + +Your Twilio Account Sid and Auth Token ([found here, in the Twilio console](https://console.twilio.com)) + +A proxy address in the form of http://127.0.0.1:8888 + +These settings are located in an .env file, like so: + +```env +ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +AUTH_TOKEN= your_auth_token + +HTTPS_PROXY=https://127.0.0.1:8888 +HTTP_PROXY=http://127.0.0.1:8888 +``` + +Here’s the full program that sends a text message and shows how it all can work together. + +```python +import os +from twilio.rest import Client +from custom_client import MyRequestClass + +from dotenv import load_dotenv +load_dotenv() + +# Custom HTTP Class +my_request_client = MyRequestClass() + +client = Client(os.getenv("ACCOUNT_SID"), os.getenv("AUTH_TOKEN"), + http_client=my_request_client) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +print('Message SID: {}'.format(message.sid)) +``` + +## What else can this technique be used for? + +Now that you know how to inject your own `http_client` into the Twilio API request pipeline, you could use this technique to add custom HTTP headers and authorization to the requests (perhaps as required by an upstream proxy server). + +You could also implement your own `http_client` to mock the Twilio API responses so your unit and integration tests can run quickly without needing to make a connection to Twilio. In fact, there’s already an example online showing [how to do exactly that with Node.js and Prism](https://www.twilio.com/docs/openapi/mock-api-generation-with-twilio-openapi-spec). + +We can’t wait to see what you build! diff --git a/docs/conf.py b/docs/conf.py index b027d92424..017b358093 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,15 +15,16 @@ # import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) from twilio import __version__ # -- Project information ----------------------------------------------------- -project = 'twilio-python' -copyright = '2019, Twilio' -author = 'Twilio' +project = "twilio-python" +copyright = "2023, Twilio" +author = "Twilio" # The short X.Y version version = __version__ @@ -41,28 +42,28 @@ # 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' + "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'] +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', + ".rst": "restructuredtext", + ".md": "markdown", } # The master toctree document. -master_doc = 'index' +master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -77,7 +78,7 @@ exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # -- Options for HTML output ------------------------------------------------- @@ -85,7 +86,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'alabaster' +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 @@ -93,7 +94,7 @@ # # html_theme_options = {} -html_static_path = ['source/_static'] +html_static_path = ["source/_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. @@ -104,15 +105,20 @@ # 'searchbox.html']``. # html_sidebars = { - '**': [ 'sidebarintro.html', 'localtoc.html', 'relations.html', - 'sourcelink.html', 'searchbox.html'] + "**": [ + "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' +htmlhelp_basename = "twilio-pythondoc" # -- Options for LaTeX output ------------------------------------------------ @@ -121,15 +127,12 @@ # 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', @@ -139,8 +142,13 @@ # (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'), + ( + master_doc, + "twilio-python.tex", + "twilio-python Documentation", + "Twilio", + "manual", + ), ] @@ -148,10 +156,7 @@ # 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) -] +man_pages = [(master_doc, "twilio-python", "twilio-python Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- @@ -160,9 +165,15 @@ # (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'), + ( + master_doc, + "twilio-python", + "twilio-python Documentation", + author, + "twilio-python", + "One line description of project.", + "Miscellaneous", + ), ] @@ -184,7 +195,7 @@ # epub_uid = '' # A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] +epub_exclude_files = ["search.html"] # -- Extension configuration ------------------------------------------------- @@ -192,4 +203,4 @@ # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'https://docs.python.org/': None} +intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} diff --git a/docs/source/_templates/sidebarintro.html b/docs/source/_templates/sidebarintro.html index a2eaf94ebc..9acc1e0e23 100644 --- a/docs/source/_templates/sidebarintro.html +++ b/docs/source/_templates/sidebarintro.html @@ -1,11 +1,13 @@ -

About twilio-python

+

About twilio-python

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

Useful Links

\ No newline at end of file +
  • + twilio-python @ GitHub +
  • + 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/requirements.txt b/requirements.txt index a52474a242..7bc9e41806 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,8 @@ -flake8 -mock -nose -six -requests>=2.0.0 -PyJWT>=1.4.2 -twine \ No newline at end of file +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 cbbb055e13..97004e4a02 --- a/setup.py +++ b/setup.py @@ -1,11 +1,6 @@ -from __future__ import with_statement from setuptools import setup, find_packages -__version__ = None -with open('twilio/__init__.py') as f: - exec(f.read()) - -with open('README.md') as f: +with open("README.md") as f: long_description = f.read() # To install the twilio-python library, open a Terminal shell, then run this @@ -18,26 +13,20 @@ setup( name="twilio", - version=__version__, + version="9.6.3", description="Twilio API client and TwiML generator", author="Twilio", - author_email="help@twilio.com", + 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=[ - "six", - "pytz", - "PyJWT >= 1.4.2", + "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" - ], - }, - packages=find_packages(exclude=['tests', 'tests.*']), + packages=find_packages(exclude=["tests", "tests.*"]), include_package_data=True, classifiers=[ "Development Status :: 5 - Production/Stable", @@ -45,16 +34,17 @@ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2.7", - "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=long_description, - long_description_content_type='text/markdown' + 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 b0390a3064..8f71514314 100644 --- a/tests/holodeck.py +++ b/tests/holodeck.py @@ -6,14 +6,12 @@ class Hologram(object): - def __init__(self, request, response): self.request = request self.response = response class Holodeck(HttpClient): - def __init__(self): self._holograms = [] self._requests = [] @@ -28,16 +26,19 @@ def requests(self): def add_standard_headers(self, request): standard_headers = { - 'User-Agent': 'twilio-python/{} (Python {})'.format( + "User-Agent": "twilio-python/{} ({} {}) Python/{}".format( __version__, - platform.python_version()), - 'X-Twilio-Client': 'python-{}'.format(__version__), - 'Accept': 'application/json', - 'Accept-Charset': 'utf-8' + 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' + 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 @@ -48,25 +49,28 @@ def assert_has_request(self, 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) @@ -75,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 c9fc143806..0000000000 --- a/tests/integration/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/accounts/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/accounts/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/accounts/v1/credential/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 1eb1b60afc..0000000000 --- a/tests/integration/accounts/v1/credential/test_aws.py +++ /dev/null @@ -1,206 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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 a868a3bcdc..0000000000 --- a/tests/integration/accounts/v1/credential/test_public_key.py +++ /dev/null @@ -1,206 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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 3f29f85bb6..0000000000 --- a/tests/integration/accounts/v1/test_credential.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/address/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 a0a886ef2c..0000000000 --- a/tests/integration/api/v2010/account/address/test_dependent_phone_number.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 17c63a928f..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_local.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 4632ac2145..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_machine_to_machine.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 647a15cd5b..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_mobile.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 5d7d3c8501..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_national.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 cf6481a5a0..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_shared_cost.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 14b5e7f240..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_toll_free.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 4bcd3c6dbc..0000000000 --- a/tests/integration/api/v2010/account/available_phone_number/test_voip.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/call/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 de6bef7142..0000000000 --- a/tests/integration/api/v2010/account/call/test_feedback.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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 3b0905bc7c..0000000000 --- a/tests/integration/api/v2010/account/call/test_feedback_summary.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries("FSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls \ - .feedback_summaries("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 823ab4e37e..0000000000 --- a/tests/integration/api/v2010/account/call/test_notification.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications("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/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications("NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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, - ''' - { - "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/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0", - "next_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "notifications": [], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0", - "next_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/call/test_payment.py b/tests/integration/api/v2010/account/call/test_payment.py deleted file mode 100644 index ad03d4b485..0000000000 --- a/tests/integration/api/v2010/account/call/test_payment.py +++ /dev/null @@ -1,131 +0,0 @@ -# coding=utf-8 -r""" -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 PaymentTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments.create(idempotency_key="idempotency_key", status_callback="https://example.com") - - values = {'IdempotencyKey': "idempotency_key", 'StatusCallback': "https://example.com", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payments.json', - data=values, - )) - - def test_start_payment_session_success_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 18 Dec 2019 20:02:01 +0000", - "date_updated": "Wed, 18 Dec 2019 20:02:01 +0000", - "sid": "PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments/PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments.create(idempotency_key="idempotency_key", status_callback="https://example.com") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments("PKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(idempotency_key="idempotency_key", status_callback="https://example.com") - - values = {'IdempotencyKey': "idempotency_key", 'StatusCallback': "https://example.com", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payments/PKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_collect_credit_card_number_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 18 Dec 2019 20:02:01 +0000", - "date_updated": "Wed, 18 Dec 2019 20:02:01 +0000", - "sid": "PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments/PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments("PKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(idempotency_key="idempotency_key", status_callback="https://example.com") - - self.assertIsNotNone(actual) - - def test_collect_credit_card_expiry_date_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 18 Dec 2019 20:02:01 +0000", - "date_updated": "Wed, 18 Dec 2019 20:02:01 +0000", - "sid": "PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments/PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments("PKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(idempotency_key="idempotency_key", status_callback="https://example.com") - - self.assertIsNotNone(actual) - - def test_complete_payment_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 18 Dec 2019 20:02:01 +0000", - "date_updated": "Wed, 18 Dec 2019 20:02:01 +0000", - "sid": "PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments/PKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payments("PKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(idempotency_key="idempotency_key", status_callback="https://example.com") - - 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 2568c3ed35..0000000000 --- a/tests/integration/api/v2010/account/call/test_recording.py +++ /dev/null @@ -1,267 +0,0 @@ -# coding=utf-8 -r""" -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_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "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:34 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "price": null, - "price_unit": null, - "duration": null, - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartCallRecordingAPI", - "status": "in-progress", - "error_code": null, - "encryption_details": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - values = {'Status': "in-progress", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_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:36 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "price": null, - "price_unit": null, - "duration": null, - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartCallRecordingAPI", - "status": "paused", - "error_code": null, - "encryption_details": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/conference/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 2995e18168..0000000000 --- a/tests/integration/api/v2010/account/conference/test_participant.py +++ /dev/null @@ -1,679 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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", - "label": null, - "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, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_by_label_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": "customer", - "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, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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_mute_participant_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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": true, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_mute_participant_by_label_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": "customer", - "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": true, - "hold": false, - "status": "complete", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_modify_participant_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_modify_participant_by_label_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": "customer", - "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, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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", - "label": "customer", - "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, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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", - "label": "customer", - "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, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_sid_as_coach_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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": "queued", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_non_e164_number_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_friendly_name_jitter_buffer_size_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_friendly_name_byoc_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "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, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(from_="+15017122661", to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_with_friendly_name_caller_id_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, - "coaching": false, - "call_sid_to_coach": null, - "label": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_delete_by_label_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Hold=True&PageSize=50&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Hold=True&PageSize=50&Page=0", - "page": 0, - "page_size": 50, - "end": 0, - "start": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Sat, 19 Feb 2011 21:07:19 +0000", - "date_updated": "Sat, 19 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "label": null, - "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": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0", - "page": 0, - "page_size": 2, - "start": 0, - "end": 1 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_read_next_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAcccccccccccccccccccccccccccccccc", - "label": null, - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 17 Feb 2011 21:07:19 +0000", - "date_updated": "Thu, 17 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAcccccccccccccccccccccccccccccccc.json" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAdddddddddddddddddddddddddddddddd", - "label": null, - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Wed, 16 Feb 2011 21:07:19 +0000", - "date_updated": "Wed, 16 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAdddddddddddddddddddddddddddddddd.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0", - "next_page_uri": null, - "previous_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0&PageToken=PBCPcccccccccccccccccccccccccccccccc", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=1&PageToken=PACPbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "page": 1, - "page_size": 2, - "start": 2, - "end": 3 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) - - def test_read_previous_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "label": null, - "conference_sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Sat, 19 Feb 2011 21:07:19 +0000", - "date_updated": "Sat, 19 Feb 2011 21:07:19 +0000", - "end_conference_on_exit": false, - "muted": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": true, - "call_sid_to_coach": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "label": null, - "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": true, - "hold": false, - "status": "connected", - "start_conference_on_enter": true, - "coaching": false, - "call_sid_to_coach": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/CAbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json" - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json?Muted=true&PageSize=2&Page=0&PageToken=PBCPcccccccccccccccccccccccccccccccc", - "page": 0, - "page_size": 2, - "start": 0, - "end": 1 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/conference/test_recording.py b/tests/integration/api/v2010/account/conference/test_recording.py deleted file mode 100644 index 5ff8101ce9..0000000000 --- a/tests/integration/api/v2010/account/conference/test_recording.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding=utf-8 -r""" -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_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - values = {'Status': "in-progress", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - data=values, - )) - - def test_update_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:39 +0000", - "start_time": "Fri, 14 Oct 2016 21:56:34 +0000", - "price": null, - "price_unit": null, - "duration": null, - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartConferenceRecordingAPI", - "status": "paused", - "error_code": null, - "encryption_details": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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", - "price": "-0.0025", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartConferenceRecordingAPI", - "status": "completed", - "error_code": null, - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings/REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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": "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", - "price": "-0.0025", - "price_unit": "USD", - "duration": "4", - "sid": "REaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source": "StartConferenceRecordingAPI", - "status": "completed", - "error_code": null, - "encryption_details": { - "encryption_public_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_cek": "OV4h6zrsxMIW7h0Zfqwfn6TI2GCNl54KALlg8wn8YB8KYZhXt6HlgvBWAmQTlfYVeLWydMiCewY0YkDDT1xmNe5huEo9vjuKBS5OmYK4CZkSx1NVv3XOGrZHpd2Pl/5WJHVhUK//AUO87uh5qnUP2E0KoLh1nyCLeGcEkXU0RfpPn/6nxjof/n6m6OzZOyeIRK4Oed5+rEtjqFDfqT0EVKjs6JAxv+f0DCc1xYRHl2yV8bahUPVKs+bHYdy4PVszFKa76M/Uae4jFA9Lv233JqWcxj+K2UoghuGhAFbV/JQIIswY2CBYI8JlVSifSqNEl9vvsTJ8bkVMm3MKbG2P7Q==", - "encryption_iv": "8I2hhNIYNTrwxfHk" - }, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 1663947d29..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 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("XFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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 097b313fb2..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_assigned_add_on.py +++ /dev/null @@ -1,208 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assigned_add_ons("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 49693f17b6..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_local.py +++ /dev/null @@ -1,186 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "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("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("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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 6ac9ba99fd..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_mobile.py +++ /dev/null @@ -1,186 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "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("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("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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 4a1c783f3b..0000000000 --- a/tests/integration/api/v2010/account/incoming_phone_number/test_toll_free.py +++ /dev/null @@ -1,186 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "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("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("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("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, - "emergency_status": "Active", - "emergency_address_sid": "ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/message/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 749a4fdaa0..0000000000 --- a/tests/integration/api/v2010/account/message/test_feedback.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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 771930db60..0000000000 --- a/tests/integration/api/v2010/account/message/test_media.py +++ /dev/null @@ -1,152 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/queue/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 3caffdc12f..0000000000 --- a/tests/integration/api/v2010/account/queue/test_member.py +++ /dev/null @@ -1,198 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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, - ''' - { - "queue_sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_front_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "queue_sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(url="https://example.com") - - values = {'Url': "https://example.com", } - - 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, - ''' - { - "queue_sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_enqueued": "Thu, 06 Dec 2018 18:42:47 +0000", - "position": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "wait_time": 143 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(url="https://example.com") - - self.assertIsNotNone(actual) - - def test_dequeue_front_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "queue_sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(url="https://example.com") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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?PageSize=50&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "queue_members": [ - { - "queue_sid": "QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_enqueued": "Mon, 17 Dec 2018 18:36:39 +0000", - "position": 1, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "wait_time": 124 - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "queue_members": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/recording/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/recording/add_on_result/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 1e40fae8d1..0000000000 --- a/tests/integration/api/v2010/account/recording/add_on_result/test_payload.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads("XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .payloads("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 6ed645a365..0000000000 --- a/tests/integration/api/v2010/account/recording/test_add_on_result.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("XRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .add_on_results("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 63d4ba52ab..0000000000 --- a/tests/integration/api/v2010/account/recording/test_transcription.py +++ /dev/null @@ -1,164 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/credential_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 10b5981dac..0000000000 --- a/tests/integration/api/v2010/account/sip/credential_list/test_credential.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/__init__.py b/tests/integration/api/v2010/account/sip/domain/auth_types/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/__init__.py b/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_credential_list_mapping.py b/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_credential_list_mapping.py deleted file mode 100644 index 33191d99c7..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_credential_list_mapping.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding=utf-8 -r""" -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 AuthCallsCredentialListMappingTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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/Auth/Calls/CredentialListMappings.json', - data=values, - )) - - 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", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Calls/CredentialListMappings.json', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/CredentialListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/CredentialListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/CredentialListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/CredentialListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Calls/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Calls/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_ip_access_control_list_mapping.py b/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_ip_access_control_list_mapping.py deleted file mode 100644 index efdf16d299..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/test_auth_calls_ip_access_control_list_mapping.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding=utf-8 -r""" -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 AuthCallsIpAccessControlListMappingTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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/Auth/Calls/IpAccessControlListMappings.json', - data=values, - )) - - 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", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .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/Auth/Calls/IpAccessControlListMappings.json', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/IpAccessControlListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/IpAccessControlListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/IpAccessControlListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Calls/IpAccessControlListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_list_mappings("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Calls/IpAccessControlListMappings/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_list_mappings("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_list_mappings("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Calls/IpAccessControlListMappings/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .calls \ - .ip_access_control_list_mappings("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/__init__.py b/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/test_auth_registrations_credential_list_mapping.py b/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/test_auth_registrations_credential_list_mapping.py deleted file mode 100644 index 2e21d273d2..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/test_auth_registrations_credential_list_mapping.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding=utf-8 -r""" -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 AuthRegistrationsCredentialListMappingTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .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/Auth/Registrations/CredentialListMappings.json', - data=values, - )) - - 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", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Registrations/CredentialListMappings.json', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Registrations/CredentialListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Registrations/CredentialListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Registrations/CredentialListMappings.json?PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "contents": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/Domains/SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Auth/Registrations/CredentialListMappings.json?PageSize=50&Page=0", - "page_size": 50, - "start": 0, - "next_page_uri": null, - "page": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Registrations/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "Thu, 30 Jul 2015 20:00:00 +0000", - "date_updated": "Thu, 30 Jul 2015 20:00:00 +0000", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SIP/Domains/SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Auth/Registrations/CredentialListMappings/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .auth \ - .registrations \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_calls_mapping.py b/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_calls_mapping.py deleted file mode 100644 index b1ede9f0c2..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_calls_mapping.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 AuthTypeCallsTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_registrations_mapping.py b/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_registrations_mapping.py deleted file mode 100644 index 22d1d491b7..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/auth_types/test_auth_registrations_mapping.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 AuthTypeRegistrationsTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/api/v2010/account/sip/domain/test_auth_types.py b/tests/integration/api/v2010/account/sip/domain/test_auth_types.py deleted file mode 100644 index 51ff659616..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/test_auth_types.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 AuthTypesTestCase(IntegrationTestCase): - pass 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 e1467297bb..0000000000 --- a/tests/integration/api/v2010/account/sip/domain/test_credential_list_mapping.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credential_list_mappings("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 bcc9160143..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 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_list_mappings("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/sip/ip_access_control_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 4d7eeab833..0000000000 --- a/tests/integration/api/v2010/account/sip/ip_access_control_list/test_ip_address.py +++ /dev/null @@ -1,238 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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": "friendly_name", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1", - "cidr_prefix_length": 32, - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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": [], - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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": "friendly_name", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1", - "cidr_prefix_length": 32, - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("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": "friendly_name", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1", - "cidr_prefix_length": 32, - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("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": "friendly_name", - "ip_access_control_list_sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1", - "cidr_prefix_length": 32, - "sid": "IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses/IPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("IPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_addresses("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 d0ee46f482..0000000000 --- a/tests/integration/api/v2010/account/sip/test_credential_list.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .credential_lists("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 e75edc80ec..0000000000 --- a/tests/integration/api/v2010/account/sip/test_domain.py +++ /dev/null @@ -1,287 +0,0 @@ -# coding=utf-8 -r""" -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("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": "IP_ACL", - "date_created": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +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", - "emergency_calling_enabled": true, - "secure": true, - "byoc_trunk_sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "emergency_caller_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "start": 0, - "end": 0, - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "domains": [], - "start": 0, - "end": 0, - "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("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("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": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +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", - "emergency_calling_enabled": true, - "secure": true, - "byoc_trunk_sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "emergency_caller_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +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", - "emergency_calling_enabled": true, - "secure": true, - "byoc_trunk_sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "emergency_caller_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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": "Mon, 20 Jul 2015 17:27:10 +0000", - "date_updated": "Mon, 20 Jul 2015 17:27:10 +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", - "emergency_calling_enabled": true, - "secure": true, - "byoc_trunk_sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "emergency_caller_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .domains("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 23b29bcc5a..0000000000 --- a/tests/integration/api/v2010/account/sip/test_ip_access_control_list.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sip \ - .ip_access_control_lists("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 2c6501cdb2..0000000000 --- a/tests/integration/api/v2010/account/test_address.py +++ /dev/null @@ -1,253 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "verified": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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, - "verified": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("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, - "verified": false, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Addresses/ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .addresses("ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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, - "verified": 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("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("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 48daef271b..0000000000 --- a/tests/integration/api/v2010/account/test_application.py +++ /dev/null @@ -1,257 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Applications.json', - )) - - 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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications.create() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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", - "next_page_uri": null, - "previous_page_uri": null, - "page_size": 1, - "page": 0, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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", - "previous_page_uri": null, - "page_size": 1, - "start": 0, - "next_page_uri": null, - "page": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Applications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .applications("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 a0aacf76f3..0000000000 --- a/tests/integration/api/v2010/account/test_authorized_connect_app.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .authorized_connect_apps("CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 2d1fa3cb85..0000000000 --- a/tests/integration/api/v2010/account/test_available_phone_number.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .available_phone_numbers("US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/api/v2010/account/test_balance.py b/tests/integration/api/v2010/account/test_balance.py deleted file mode 100644 index 1ba015ef12..0000000000 --- a/tests/integration/api/v2010/account/test_balance.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -r""" -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 BalanceTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .balance.fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Balance.json', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "balance": "0.05", - "currency": "USD" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .balance.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 b1df199181..0000000000 --- a/tests/integration/api/v2010/account/test_call.py +++ /dev/null @@ -1,628 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) - - def test_create_with_twiml_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", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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": "billingreferencetag", - "answered_by": "machine_start", - "api_version": "2010-04-01", - "caller_name": "callerid", - "date_created": "Fri, 18 Oct 2019 17:00:00 +0000", - "date_updated": "Fri, 18 Oct 2019 17:01:00 +0000", - "direction": "outbound-api", - "duration": "4", - "end_time": "Fri, 18 Oct 2019 17:03:00 +0000", - "forwarded_from": "calledvia", - "from": "+13051416799", - "from_formatted": "(305) 141-6799", - "group_sid": "GPdeadbeefdeadbeefdeadbeefdeadbeef", - "parent_call_sid": "CAdeadbeefdeadbeefdeadbeefdeadbeef", - "phone_number_sid": "PNdeadbeefdeadbeefdeadbeefdeadbeef", - "price": "-0.200", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Fri, 18 Oct 2019 17:02:00 +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", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+13051913581", - "to_formatted": "(305) 191-3581", - "trunk_sid": "TKdeadbeefdeadbeefdeadbeefdeadbeef", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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_page1_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": "billingreferencetag1", - "answered_by": "machine_start", - "api_version": "2010-04-01", - "caller_name": "callerid1", - "date_created": "Fri, 18 Oct 2019 17:00:00 +0000", - "date_updated": "Fri, 18 Oct 2019 17:01:00 +0000", - "direction": "outbound-api", - "duration": "4", - "end_time": "Fri, 18 Oct 2019 17:03:00 +0000", - "forwarded_from": "calledvia1", - "from": "+13051416799", - "from_formatted": "(305) 141-6799", - "group_sid": "GPdeadbeefdeadbeefdeadbeefdeadbeef", - "parent_call_sid": "CAdeadbeefdeadbeefdeadbeefdeadbeef", - "phone_number_sid": "PNdeadbeefdeadbeefdeadbeefdeadbeef", - "price": "-0.200", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Fri, 18 Oct 2019 17:02:00 +0000", - "status": "completed", - "subresource_uris": { - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+13051913581", - "to_formatted": "(305) 191-3581", - "trunk_sid": "TKdeadbeefdeadbeefdeadbeefdeadbeef", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": "billingreferencetag2", - "answered_by": "human", - "api_version": "2010-04-01", - "caller_name": "callerid2", - "date_created": "Fri, 18 Oct 2019 16:00:00 +0000", - "date_updated": "Fri, 18 Oct 2019 16:01:00 +0000", - "direction": "inbound", - "duration": "3", - "end_time": "Fri, 18 Oct 2019 16:03:00 +0000", - "forwarded_from": "calledvia2", - "from": "+13051416798", - "from_formatted": "(305) 141-6798", - "group_sid": "GPdeadbeefdeadbeefdeadbeefdeadbeee", - "parent_call_sid": "CAdeadbeefdeadbeefdeadbeefdeadbeee", - "phone_number_sid": "PNdeadbeefdeadbeefdeadbeefdeadbeee", - "price": "-0.100", - "price_unit": "JPY", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0", - "start_time": "Fri, 18 Oct 2019 16:02:00 +0000", - "status": "completed", - "subresource_uris": { - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Recordings.json", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Payments.json" - }, - "to": "+13051913580", - "to_formatted": "(305) 191-3580", - "trunk_sid": "TKdeadbeefdeadbeefdeadbeefdeadbeef", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0.json", - "queue_time": "1000" - } - ], - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EndTime=2009-01-02&PageSize=2&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 2, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EndTime=2009-01-02&PageSize=2&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_read_full_page2_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": "billingreferencetag1", - "answered_by": "machine_start", - "api_version": "2010-04-01", - "caller_name": "callerid1", - "date_created": "Fri, 18 Oct 2019 17:00:00 +0000", - "date_updated": "Fri, 18 Oct 2019 17:01:00 +0000", - "direction": "outbound-api", - "duration": "4", - "end_time": "Fri, 18 Oct 2019 17:03:00 +0000", - "forwarded_from": "calledvia1", - "from": "+13051416799", - "from_formatted": "(305) 141-6799", - "group_sid": "GPdeadbeefdeadbeefdeadbeefdeadbeef", - "parent_call_sid": "CAdeadbeefdeadbeefdeadbeefdeadbeef", - "phone_number_sid": "PNdeadbeefdeadbeefdeadbeefdeadbeef", - "price": "-0.200", - "price_unit": "USD", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start_time": "Fri, 18 Oct 2019 17:02:00 +0000", - "status": "completed", - "subresource_uris": { - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+13051913581", - "to_formatted": "(305) 191-3581", - "trunk_sid": "TKdeadbeefdeadbeefdeadbeefdeadbeef", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "annotation": "billingreferencetag2", - "answered_by": "human", - "api_version": "2010-04-01", - "caller_name": "callerid2", - "date_created": "Fri, 18 Oct 2019 16:00:00 +0000", - "date_updated": "Fri, 18 Oct 2019 16:01:00 +0000", - "direction": "inbound", - "duration": "3", - "end_time": "Fri, 18 Oct 2019 16:03:00 +0000", - "forwarded_from": "calledvia2", - "from": "+13051416798", - "from_formatted": "(305) 141-6798", - "group_sid": "GPdeadbeefdeadbeefdeadbeefdeadbeee", - "parent_call_sid": "CAdeadbeefdeadbeefdeadbeefdeadbeee", - "phone_number_sid": "PNdeadbeefdeadbeefdeadbeefdeadbeee", - "price": "-0.100", - "price_unit": "JPY", - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0", - "start_time": "Fri, 18 Oct 2019 16:02:00 +0000", - "status": "completed", - "subresource_uris": { - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json", - "notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Notifications.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Recordings.json", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0/Payments.json" - }, - "to": "+13051913580", - "to_formatted": "(305) 191-3580", - "trunk_sid": "TKdeadbeefdeadbeefdeadbeefdeadbeef", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0.json", - "queue_time": "1000" - } - ], - "end": 3, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&From=%2B987654321&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&To=%2B123456789&StartTime=2008-01-02&EndTime=2009-01-02&PageSize=2&Page=0", - "next_page_uri": null, - "page": 1, - "page_size": 2, - "previous_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&From=%2B987654321&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&To=%2B123456789&StartTime=2008-01-02&EndTime=2009-01-02&PageSize=2&Page=0&PageToken=PBCAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start": 2, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&From=%2B987654321&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&To=%2B123456789&StartTime=2008-01-02&EndTime=2009-01-02&PageSize=2&Page=1&PageToken=PACAdeadbeefdeadbeefdeadbeefdeadbeef" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_dates_greater_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&To=%2B123456789&EndTime%3E=2009-01-02&From=%2B987654321&StartTime%3E=2008-01-02&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=2&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 2, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?Status=completed&To=%2B123456789&EndTime%3E=2009-01-02&From=%2B987654321&StartTime%3E=2008-01-02&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=2&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_dates_less_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?EndTime%3C=2009-01-02&Status=completed&From=%2B987654321&To=%2B123456789&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartTime%3C=2008-01-02&PageSize=2&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 2, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?EndTime%3C=2009-01-02&Status=completed&From=%2B987654321&To=%2B123456789&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartTime%3C=2008-01-02&PageSize=2&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls.list() - - self.assertIsNotNone(actual) - - def test_read_empty_date_fun_date_formats_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "calls": [], - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?EndTime%3C=2019-06-11+22%3A05%3A25.000&Status=completed&From=%2B987654321&To=%2B123456789&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartTime%3C=06%2F11%2F2019+22%3A05%3A25+MST&PageSize=2&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 2, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls.json?EndTime%3C=2019-06-11+22%3A05%3A25.000&Status=completed&From=%2B987654321&To=%2B123456789&ParentCallSid=CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartTime%3C=06%2F11%2F2019+22%3A05%3A25+MST&PageSize=2&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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", - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Feedback.json", - "feedback_summaries": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/FeedbackSummary.json", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_cancel_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": "canceled", - "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", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_posttwiml_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": "canceled", - "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", - "payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json" - }, - "to": "+14158675309", - "to_formatted": "(415) 867-5309", - "trunk_sid": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "queue_time": "1000" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .calls("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 58bab25fea..0000000000 --- a/tests/integration/api/v2010/account/test_conference.py +++ /dev/null @@ -1,444 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences/CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_fetch_valid_mixer_zone_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-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", - "reason_conference_ended": "last-participant-left", - "call_sid_ending_conference": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_valid_region_in_progress_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-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": "au1", - "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", - "reason_conference_ended": null, - "call_sid_ending_conference": null - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_without_mixer_zone_integer_status_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-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", - "reason_conference_ended": "participant-with-end-conference-on-exit-left", - "call_sid_ending_conference": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_unknown_mixer_zone_init_integer_status_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-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": "unknown", - "status": "init", - "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", - "reason_conference_ended": "participant-with-end-conference-on-exit-left", - "call_sid_ending_conference": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences.json', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=init&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=50&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=init&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=50&Page=0", - "page": 0, - "page_size": 50, - "start": 0, - "end": 0 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [ - { - "status": "in-progress", - "region": "jp1", - "sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "Sat, 03 Jan 2015 11:23:45 +0000", - "date_created": "Sat, 03 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "unknown", - "sid": "CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "date_updated": "Fri, 02 Jan 2015 11:23:45 +0000", - "date_created": "Fri, 02 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "us1", - "sid": "CFcccccccccccccccccccccccccccccccc", - "date_updated": "Thu, 01 Jan 2015 11:23:45 +0000", - "date_created": "Thu, 01 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0", - "page": 0, - "page_size": 3, - "start": 0, - "end": 2 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.assertIsNotNone(actual) - - def test_read_next_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [ - { - "status": "in-progress", - "region": "jp1", - "sid": "CFdddddddddddddddddddddddddddddddd", - "date_updated": "Thu, 01 Jan 2015 10:23:45 +0000", - "date_created": "Thu, 01 Jan 2015 10:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFdddddddddddddddddddddddddddddddd/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFdddddddddddddddddddddddddddddddd/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFdddddddddddddddddddddddddddddddd.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "unknown", - "sid": "CFeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", - "date_updated": "Thu, 01 Jan 2015 09:23:45 +0000", - "date_created": "Thu, 01 Jan 2015 09:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "us1", - "sid": "CFffffffffffffffffffffffffffffffff", - "date_updated": "Thu, 01 Jan 2015 08:23:45 +0000", - "date_created": "Thu, 01 Jan 2015 08:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFffffffffffffffffffffffffffffffff/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFffffffffffffffffffffffffffffffff/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFffffffffffffffffffffffffffffffff.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0", - "next_page_uri": null, - "previous_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0&PageToken=PBCFdddddddddddddddddddddddddddddddd", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=1&PageToken=PACFcccccccccccccccccccccccccccccccc", - "page": 1, - "page_size": 3, - "start": 3, - "end": 5 - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences.list() - - self.assertIsNotNone(actual) - - def test_read_previous_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conferences": [ - { - "status": "in-progress", - "region": "jp1", - "sid": "CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "Sat, 03 Jan 2015 11:23:45 +0000", - "date_created": "Sat, 03 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "unknown", - "sid": "CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "date_updated": "Fri, 02 Jan 2015 11:23:45 +0000", - "date_created": "Fri, 02 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - }, - { - "status": "in-progress", - "region": "us1", - "sid": "CFcccccccccccccccccccccccccccccccc", - "date_updated": "Thu, 01 Jan 2015 11:23:45 +0000", - "date_created": "Thu, 01 Jan 2015 11:23:45 +0000", - "subresource_uris": { - "participants": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc/Participants.json", - "recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc/Recordings.json" - }, - "friendly_name": "friendly_name", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences/CFcccccccccccccccccccccccccccccccc.json", - "api_version": "2010-04-01", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason_conference_ended": null, - "call_sid_ending_conference": null - } - ], - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0", - "next_page_uri": null, - "previous_page_uri": null, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Conferences.json?Status=in-progress&DateUpdated%3E=2018-11-12&DateUpdated%3C=2018-11-11&DateCreated=2008-01-03&FriendlyName=friendly_name&DateUpdated=2018-11-13&DateCreated%3C=2008-01-01&DateCreated%3E=2008-01-02&PageSize=3&Page=0&PageToken=PBCFdddddddddddddddddddddddddddddddd", - "page": 0, - "page_size": 3, - "start": 0, - "end": 2 - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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", - "reason_conference_ended": "conference-ended-via-api", - "call_sid_ending_conference": null - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .conferences("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 1a6f7e67dd..0000000000 --- a/tests/integration/api/v2010/account/test_connect_app.py +++ /dev/null @@ -1,184 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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", - "next_page_uri": null, - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ConnectApps/CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .connect_apps("CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 216e1beaa1..0000000000 --- a/tests/integration/api/v2010/account/test_incoming_phone_number.py +++ /dev/null @@ -1,351 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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": { - "voice": true, - "sms": false, - "mms": true, - "fax": false - }, - "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": true, - "voice_fallback_method": "POST", - "voice_fallback_url": null, - "voice_method": "POST", - "voice_url": null, - "voice_receive_mode": "voice", - "status": "in-use", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "assigned_add_ons": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json", - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json", - "mobile": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json", - "toll_free": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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": { - "voice": true, - "sms": false, - "mms": true, - "fax": false - }, - "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, - "voice_receive_mode": "voice", - "status": "in-use", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "subresource_uris": { - "assigned_add_ons": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json", - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json", - "mobile": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json", - "toll_free": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .incoming_phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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, - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "voice_receive_mode": "voice", - "status": "in-use", - "subresource_uris": { - "assigned_add_ons": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json", - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json", - "mobile": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json", - "toll_free": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json" - } - } - ], - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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": [], - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers.json?PageSize=1" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("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, - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "voice_receive_mode": "voice", - "status": "in-use", - "subresource_uris": { - "assigned_add_ons": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json", - "local": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Local.json", - "mobile": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/Mobile.json", - "toll_free": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/TollFree.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 d89bb29ae2..0000000000 --- a/tests/integration/api/v2010/account/test_key.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 974d92e46e..0000000000 --- a/tests/integration/api/v2010/account/test_message.py +++ /dev/null @@ -1,449 +0,0 @@ -# coding=utf-8 -r""" -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("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": "Hello! \\ud83d\\udc4d", - "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": null, - "price_unit": null, - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(to="+15558675310") - - self.assertIsNotNone(actual) - - def test_create_wo_service_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "Hello! \\ud83d\\udc4d", - "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": null, - "num_media": "0", - "num_segments": "1", - "price": null, - "price_unit": null, - "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("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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": "testing", - "date_created": "Fri, 24 May 2019 17:18:27 +0000", - "date_sent": "Fri, 24 May 2019 17:18:28 +0000", - "date_updated": "Fri, 24 May 2019 17:18:28 +0000", - "direction": "outbound-api", - "error_code": 30007, - "error_message": "Carrier violation", - "from": "+12019235161", - "messaging_service_sid": "MGdeadbeefdeadbeefdeadbeefdeadbeef", - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMb7c0a2ce80504485a6f653a7110836f5", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMb7c0a2ce80504485a6f653a7110836f5/Media.json", - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMb7c0a2ce80504485a6f653a7110836f5/Feedback.json" - }, - "to": "+18182008801", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMb7c0a2ce80504485a6f653a7110836f5.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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_page1_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 1, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 2, - "previous_page_uri": null, - "messages": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "testing", - "date_created": "Fri, 24 May 2019 17:44:46 +0000", - "date_sent": "Fri, 24 May 2019 17:44:50 +0000", - "date_updated": "Fri, 24 May 2019 17:44:50 +0000", - "direction": "outbound-api", - "error_code": null, - "error_message": null, - "from": "+12019235161", - "messaging_service_sid": null, - "num_media": "0", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "SMded05904ccb347238880ca9264e8fe1c", - "status": "sent", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMded05904ccb347238880ca9264e8fe1c/Media.json", - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMded05904ccb347238880ca9264e8fe1c/Feedback.json" - }, - "to": "+18182008801", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMded05904ccb347238880ca9264e8fe1c.json" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "api_version": "2010-04-01", - "body": "look mom I have media!", - "date_created": "Fri, 24 May 2019 17:44:46 +0000", - "date_sent": "Fri, 24 May 2019 17:44:49 +0000", - "date_updated": "Fri, 24 May 2019 17:44:49 +0000", - "direction": "inbound", - "error_code": 30004, - "error_message": "Message blocked", - "from": "+12019235161", - "messaging_service_sid": null, - "num_media": "3", - "num_segments": "1", - "price": "-0.00750", - "price_unit": "USD", - "sid": "MMc26223853f8c46b4ab7dfaa6abba0a26", - "status": "received", - "subresource_uris": { - "media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26/Media.json", - "feedback": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26/Feedback.json" - }, - "to": "+18182008801", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26.json" - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_less_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3C=2008-01-02&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3C=2008-01-02&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_equals_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent=2008-01-02&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent=2008-01-02&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_greater_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_greater_format1_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=06%2F11%2F2019+22%3A05%3A25+MST&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=06%2F11%2F2019+22%3A05%3A25+MST&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_greater_format2_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2019-06-11+22%3A05%3A25.000&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2019-06-11+22%3A05%3A25.000&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) - - def test_read_empty_sentdate_greater_format3_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end": 0, - "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=Wed%2C+19+Jun+2019+22%3A04%3A00+-0000&PageSize=25&Page=0", - "next_page_uri": null, - "page": 0, - "page_size": 25, - "previous_page_uri": null, - "messages": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=Wed%2C+19+Jun+2019+22%3A04%3A00+-0000&PageSize=25&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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": "Hello, this is trash Benson cut and pasted and probably does not do anything useful! \\ud83d\\udc4d", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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 0dc9e2ea07..0000000000 --- a/tests/integration/api/v2010/account/test_new_key.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 4b92af496d..0000000000 --- a/tests/integration/api/v2010/account/test_new_signing_key.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 c6a475b59c..0000000000 --- a/tests/integration/api/v2010/account/test_notification.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications("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": "Response body from your webhook URL as a string.", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications("NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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", - "previous_page_uri": null, - "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.json" - } - ], - "page": 0, - "page_size": 1, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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", - "next_page_uri": null, - "notifications": [], - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 7958210ca3..0000000000 --- a/tests/integration/api/v2010/account/test_outgoing_caller_id.py +++ /dev/null @@ -1,172 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("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, - ''' - { - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "(415) 867-5309", - "phone_number": "+141586753096", - "date_created": "Fri, 21 Aug 2009 00:11:24 +0000", - "date_updated": "Fri, 21 Aug 2009 00:11:24 +0000", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("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": "friendly_name", - "phone_number": "+141586753096", - "sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .outgoing_caller_ids("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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?PageSize=50&Page=0", - "next_page_uri": null, - "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, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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?PageSize=50&Page=0", - "next_page_uri": null, - "outgoing_caller_ids": [], - "page": 0, - "page_size": 50, - "previous_page_uri": null, - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OutgoingCallerIds.json?PageSize=50&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 698ff71249..0000000000 --- a/tests/integration/api/v2010/account/test_queue.py +++ /dev/null @@ -1,228 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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", - "subresource_uris": { - "members": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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", - "subresource_uris": { - "members": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queues("QUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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", - "next_page_uri": null, - "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", - "subresource_uris": { - "members": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - } - ], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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", - "next_page_uri": null, - "page": 0, - "page_size": 1, - "previous_page_uri": null, - "queues": [], - "start": 0, - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues.json?PageSize=1&Page=0" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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("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", - "subresource_uris": { - "members": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queues/QUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members.json" - } - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 d767c667da..0000000000 --- a/tests/integration/api/v2010/account/test_recording.py +++ /dev/null @@ -1,175 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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", - "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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("REXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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", - "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("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("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 fed8962a32..0000000000 --- a/tests/integration/api/v2010/account/test_short_code.py +++ /dev/null @@ -1,170 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 9999debb3d..0000000000 --- a/tests/integration/api/v2010/account/test_signing_key.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .signing_keys("SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 17a001515a..0000000000 --- a/tests/integration/api/v2010/account/test_sip.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 c34d07342d..0000000000 --- a/tests/integration/api/v2010/account/test_token.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -r""" -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("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, - ''' - { - "username": "dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269", - "ice_servers": [ - { - "url": "stun:global.stun.twilio.com:3478?transport=udp", - "urls": "stun:global.stun.twilio.com:3478?transport=udp" - }, - { - "username": "dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269", - "credential": "tE2DajzSJwnsSbc123", - "url": "turn:global.turn.twilio.com:3478?transport=udp", - "urls": "turn:global.turn.twilio.com:3478?transport=udp" - }, - { - "username": "dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269", - "credential": "tE2DajzSJwnsSbc123", - "url": "turn:global.turn.twilio.com:3478?transport=tcp", - "urls": "turn:global.turn.twilio.com:3478?transport=tcp" - }, - { - "username": "dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269", - "credential": "tE2DajzSJwnsSbc123", - "url": "turn:global.turn.twilio.com:443?transport=tcp", - "urls": "turn:global.turn.twilio.com:443?transport=tcp" - } - ], - "date_updated": "Fri, 01 May 2020 01:42:57 +0000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ttl": "86400", - "date_created": "Fri, 01 May 2020 01:42:57 +0000", - "password": "tE2DajzSJwnsSbc123" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 513a1392ed..0000000000 --- a/tests/integration/api/v2010/account/test_transcription.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .transcriptions("TRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 4e28047a0d..0000000000 --- a/tests/integration/api/v2010/account/test_usage.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 83b8f2b9bc..0000000000 --- a/tests/integration/api/v2010/account/test_validation_request.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -r""" -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("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": "111111" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/usage/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/api/v2010/account/usage/record/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 2d825c5232..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_all_time.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 c4ac2822be..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_daily.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 e40bc8010b..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_last_month.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 c6504ae42f..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_monthly.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 78379be815..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_this_month.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 66bf13eb9b..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_today.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 0fb4ccfc5a..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_yearly.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 7812444f2d..0000000000 --- a/tests/integration/api/v2010/account/usage/record/test_yesterday.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 390bb23a36..0000000000 --- a/tests/integration/api/v2010/account/usage/test_record.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "as_of": "2019-06-24T22:32:49+00:00", - "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("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("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 e254f9423d..0000000000 --- a/tests/integration/api/v2010/account/usage/test_trigger.py +++ /dev/null @@ -1,265 +0,0 @@ -# coding=utf-8 -r""" -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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers("UTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.create(callback_url="https://example.com", trigger_value="trigger_value", usage_category="agent-conference") - - values = { - 'CallbackUrl': "https://example.com", - 'TriggerValue': "trigger_value", - 'UsageCategory': "agent-conference", - } - - 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("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .usage \ - .triggers.create(callback_url="https://example.com", trigger_value="trigger_value", usage_category="agent-conference") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.api.v2010.accounts("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("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("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 c1dc77e7aa..0000000000 --- a/tests/integration/api/v2010/test_account.py +++ /dev/null @@ -1,313 +0,0 @@ -# coding=utf-8 -r""" -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", - "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.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("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", - "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("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?FriendlyName=friendly_name&Status=active&PageSize=50&Page=0", - "end": 0, - "previous_page_uri": null, - "accounts": [], - "uri": "/2010-04-01/Accounts.json?FriendlyName=friendly_name&Status=active&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?FriendlyName=friendly_name&Status=active&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", - "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ], - "uri": "/2010-04-01/Accounts.json?FriendlyName=friendly_name&Status=active&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("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": "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", - "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_with_numeric_status_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", - "balance": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Balance.json" - }, - "type": "Full", - "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" - } - ''' - )) - - actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/__init__.py b/tests/integration/autopilot/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/autopilot/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/autopilot/v1/__init__.py b/tests/integration/autopilot/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/autopilot/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/autopilot/v1/assistant/__init__.py b/tests/integration/autopilot/v1/assistant/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/autopilot/v1/assistant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/autopilot/v1/assistant/field_type/__init__.py b/tests/integration/autopilot/v1/assistant/field_type/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/autopilot/v1/assistant/field_type/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/autopilot/v1/assistant/field_type/test_field_value.py b/tests/integration/autopilot/v1/assistant/field_type/test_field_value.py deleted file mode 100644 index b871f7081b..0000000000 --- a/tests/integration/autopilot/v1/assistant/field_type/test_field_value.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues/UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "field_values": [], - "meta": { - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?Language=language&PageSize=50&Page=0", - "page_size": 50, - "previous_page_url": null, - "key": "field_values", - "page": 0, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?Language=language&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?Language=language&PageSize=50&Page=0", - "page_size": 50, - "previous_page_url": null, - "key": "field_values", - "page": 0, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues?Language=language&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values.create(language="language", value="value") - - values = {'Language': "language", 'Value': "value", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldValues/UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/task/__init__.py b/tests/integration/autopilot/v1/assistant/task/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/autopilot/v1/assistant/task/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/autopilot/v1/assistant/task/test_field.py b/tests/integration/autopilot/v1/assistant/task/test_field.py deleted file mode 100644 index bf69802d6f..0000000000 --- a/tests/integration/autopilot/v1/assistant/task/test_field.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fields": [], - "meta": { - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "key": "fields", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fields": [ - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ], - "meta": { - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "key": "fields", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/task/test_sample.py b/tests/integration/autopilot/v1/assistant/task/test_sample.py deleted file mode 100644 index 87b4fb8e20..0000000000 --- a/tests/integration/autopilot/v1/assistant/task/test_sample.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "samples": [], - "meta": { - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "samples": [ - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.create(language="language", tagged_text="tagged_text") - - values = {'Language': "language", 'TaggedText': "tagged_text", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/task/test_task_actions.py b/tests/integration/autopilot/v1/assistant/task/test_task_actions.py deleted file mode 100644 index f08ee7f940..0000000000 --- a/tests/integration/autopilot/v1/assistant/task/test_task_actions.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding=utf-8 -r""" -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 TaskActionsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Actions', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDdddddddddddddddddddddddddddddddd", - "data": {}, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDdddddddddddddddddddddddddddddddd/Actions" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Actions', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDdddddddddddddddddddddddddddddddd", - "data": {}, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDdddddddddddddddddddddddddddddddd/Actions" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/v1/assistant/task/test_task_statistics.py b/tests/integration/autopilot/v1/assistant/task/test_task_statistics.py deleted file mode 100644 index 84a83369ef..0000000000 --- a/tests/integration/autopilot/v1/assistant/task/test_task_statistics.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -r""" -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 TaskStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "samples_count": 0, - "fields_count": 0 - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_defaults.py b/tests/integration/autopilot/v1/assistant/test_defaults.py deleted file mode 100644 index 0bed430743..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_defaults.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -r""" -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 DefaultsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .defaults().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Defaults', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": {}, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .defaults().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .defaults().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Defaults', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults", - "data": {} - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .defaults().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_dialogue.py b/tests/integration/autopilot/v1/assistant/test_dialogue.py deleted file mode 100644 index 049fed4891..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_dialogue.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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 DialogueTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dialogues("UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Dialogues/UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UKkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues/UKkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", - "data": {} - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dialogues("UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_field_type.py b/tests/integration/autopilot/v1/assistant/test_field_type.py deleted file mode 100644 index 45ee4729a6..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_field_type.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "first_page_url": "https://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes?PageSize=50&Page=0", - "first_page_url": "https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "links": { - "field_values": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes/UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldValues" - }, - "sid": "UBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FieldTypes/UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_model_build.py b/tests/integration/autopilot/v1/assistant/test_model_build.py deleted file mode 100644 index 9a1ef3b34a..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_model_build.py +++ /dev/null @@ -1,219 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "key": "model_builds", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "next_page_url": null, - "previous_page_url": null, - "page_size": 50 - }, - "model_builds": [] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds?PageSize=50&Page=0", - "first_page_url": "https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ModelBuilds/UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_query.py b/tests/integration/autopilot/v1/assistant/test_query.py deleted file mode 100644 index 12c08cf53f..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_query.py +++ /dev/null @@ -1,274 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/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": { - "task": "name", - "fields": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "voice", - "dialogue_sid": "UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/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://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DialogueSid=UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DialogueSid=UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("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": { - "task": "name", - "fields": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": null, - "dialogue_sid": "UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "previous_page_url": null, - "next_page_url": null, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DialogueSid=UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DialogueSid=UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries.create(language="language", query="query") - - values = {'Language': "language", 'Query': "query", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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": { - "task": "name", - "fields": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "voice", - "dialogue_sid": null - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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": { - "task": "name", - "fields": [ - { - "name": "name", - "value": "value", - "type": "type" - } - ] - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries/UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_channel": "sms", - "dialogue_sid": "UKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Queries/UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_style_sheet.py b/tests/integration/autopilot/v1/assistant/test_style_sheet.py deleted file mode 100644 index 63a0b05b70..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_style_sheet.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -r""" -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 StyleSheetTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/StyleSheet', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": {}, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/StyleSheet', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "data": {} - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_task.py b/tests/integration/autopilot/v1/assistant/test_task.py deleted file mode 100644 index 6f279538b5..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_task.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "tasks", - "page_size": 50, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "previous_page_url": null - }, - "tasks": [] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "tasks", - "page_size": 50, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "previous_page_url": null - }, - "tasks": [ - { - "unique_name": "unique_name", - "links": { - "fields": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/assistant/test_webhook.py b/tests/integration/autopilot/v1/assistant/test_webhook.py deleted file mode 100644 index 043cbcefca..0000000000 --- a/tests/integration/autopilot/v1/assistant/test_webhook.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "unique_name": "unique_name", - "events": "ondialogueend", - "webhook_url": "https://example.com/url", - "webhook_method": "POST" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "webhooks", - "page_size": 50, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "previous_page_url": null - }, - "webhooks": [] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "webhooks", - "page_size": 50, - "next_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "previous_page_url": null - }, - "webhooks": [ - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "unique_name": "unique_name", - "events": "ondialogueend", - "webhook_url": "https://example.com/url", - "webhook_method": "POST" - } - ] - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(unique_name="unique_name", events="events", webhook_url="https://example.com") - - values = {'UniqueName': "unique_name", 'Events': "events", 'WebhookUrl': "https://example.com", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "unique_name": "unique_name", - "events": "ondialogueend", - "webhook_url": "https://example.com/url", - "webhook_method": "POST" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(unique_name="unique_name", events="events", webhook_url="https://example.com") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "unique_name": "unique_name", - "events": "ondialogueend", - "webhook_url": "https://example.com/url", - "webhook_method": "POST" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("UMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/test_assistant.py b/tests/integration/autopilot/v1/test_assistant.py deleted file mode 100644 index 15320fae5c..0000000000 --- a/tests/integration/autopilot/v1/test_assistant.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/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, - "development_stage": "in-development", - "needs_model_build": false, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "style_sheet": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "defaults": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults", - "dialogues": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "webhooks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://autopilot.twilio.com/v1/Assistants', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "assistants": [], - "meta": { - "first_page_url": "https://autopilot.twilio.com/v1/Assistants?PageSize=50&Page=0", - "key": "assistants", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.autopilot.v1.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, - "development_stage": "in-development", - "needs_model_build": false, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "style_sheet": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "defaults": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults", - "dialogues": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "webhooks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ], - "meta": { - "first_page_url": "https://autopilot.twilio.com/v1/Assistants?PageSize=50&Page=0", - "key": "assistants", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://autopilot.twilio.com/v1/Assistants?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.autopilot.v1.assistants.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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, - "development_stage": "in-development", - "needs_model_build": false, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "style_sheet": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "defaults": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults", - "dialogues": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "webhooks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/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, - "development_stage": "in-development", - "needs_model_build": false, - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "style_sheet": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "defaults": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Defaults", - "dialogues": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "webhooks": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - }, - "url": "https://autopilot.twilio.com/v1/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://autopilot.twilio.com/v1/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.autopilot.v1.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/autopilot/v1/test_restore_assistant.py b/tests/integration/autopilot/v1/test_restore_assistant.py deleted file mode 100644 index 9322118405..0000000000 --- a/tests/integration/autopilot/v1/test_restore_assistant.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding=utf-8 -r""" -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 RestoreAssistantTestCase(IntegrationTestCase): - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.autopilot.v1.restore_assistant.update(assistant="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Assistant': "UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://autopilot.twilio.com/v1/Assistants/Restore', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-07-04T08:34:00Z", - "date_updated": "2017-07-04T08:34:00Z", - "unique_name": "so-so-unique", - "friendly_name": "so so friendly", - "needs_model_build": false, - "latest_model_build_sid": null, - "log_queries": true, - "development_stage": "in-development", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.autopilot.v1.restore_assistant.update(assistant="UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) diff --git a/tests/integration/bulkexports/__init__.py b/tests/integration/bulkexports/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/bulkexports/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/bulkexports/v1/__init__.py b/tests/integration/bulkexports/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/bulkexports/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/bulkexports/v1/export/__init__.py b/tests/integration/bulkexports/v1/export/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/bulkexports/v1/export/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/bulkexports/v1/export/test_day.py b/tests/integration/bulkexports/v1/export/test_day.py deleted file mode 100644 index c21bead547..0000000000 --- a/tests/integration/bulkexports/v1/export/test_day.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding=utf-8 -r""" -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_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports("resource_type") \ - .days("day").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Days/day', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "redirect_to": "https://www.twilio.com" - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .days("day").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports("resource_type") \ - .days.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Days', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "days": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://bulkexports.twilio.com/v1/Exports/Calls/Days?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://bulkexports.twilio.com/v1/Exports/Calls/Days?PageSize=50&Page=0", - "next_page_url": null, - "key": "days" - } - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .days.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "days": [ - { - "day": "2017-04-01", - "size": 100, - "resource_type": "Calls", - "create_date": "2017-04-02", - "friendly_name": "friendly_name" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://bulkexports.twilio.com/v1/Exports/Calls/Days?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://bulkexports.twilio.com/v1/Exports/Calls/Days?PageSize=50&Page=0", - "next_page_url": null, - "key": "days" - } - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .days.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/bulkexports/v1/export/test_export_custom_job.py b/tests/integration/bulkexports/v1/export/test_export_custom_job.py deleted file mode 100644 index ff28665f7e..0000000000 --- a/tests/integration/bulkexports/v1/export/test_export_custom_job.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -r""" -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 ExportCustomJobTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports("resource_type") \ - .export_custom_jobs.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Jobs', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Jobs?PageSize=50&Page=0", - "page_size": 50, - "key": "jobs", - "first_page_url": "https://bulkexports.twilio.com/v1/Exports/Messages/Jobs?PageSize=50&Page=0", - "next_page_url": null, - "page": 0 - }, - "jobs": [] - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .export_custom_jobs.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Jobs?PageSize=50&Page=0", - "page_size": 50, - "key": "jobs", - "first_page_url": "https://bulkexports.twilio.com/v1/Exports/Messages/Jobs?PageSize=50&Page=0", - "next_page_url": null, - "page": 0 - }, - "jobs": [ - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "webhook_method": "webhook_method", - "details": {}, - "end_day": "end_day", - "webhook_url": "webhook_url", - "email": "email", - "resource_type": "resource_type" - } - ] - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .export_custom_jobs.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports("resource_type") \ - .export_custom_jobs.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Jobs', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "webhook_method": "webhook_method", - "details": {}, - "end_day": "end_day", - "webhook_url": "webhook_url", - "email": "email", - "resource_type": "resource_type" - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type") \ - .export_custom_jobs.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/bulkexports/v1/export/test_job.py b/tests/integration/bulkexports/v1/export/test_job.py deleted file mode 100644 index 4b05b0665b..0000000000 --- a/tests/integration/bulkexports/v1/export/test_job.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -r""" -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 JobTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/Jobs/JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://bulkexports.twilio.com/v1/Exports/Jobs/JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "end_day": "end_day", - "details": {}, - "webhook_url": "webhook_url", - "webhook_method": "webhook_method", - "email": "email", - "resource_type": "resource_type" - } - ''' - )) - - actual = self.client.bulkexports.v1.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://bulkexports.twilio.com/v1/Exports/Jobs/JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.bulkexports.v1.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/bulkexports/v1/test_export.py b/tests/integration/bulkexports/v1/test_export.py deleted file mode 100644 index f71185711c..0000000000 --- a/tests/integration/bulkexports/v1/test_export.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -r""" -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.bulkexports.v1.exports("resource_type").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/resource_type', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "resource_type": "Calls", - "url": "https://bulkexports.twilio.com/v1/Exports/Calls", - "links": { - "days": "https://bulkexports.twilio.com/v1/Exports/Calls/Days" - } - } - ''' - )) - - actual = self.client.bulkexports.v1.exports("resource_type").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/bulkexports/v1/test_export_configuration.py b/tests/integration/bulkexports/v1/test_export_configuration.py deleted file mode 100644 index 05f807e311..0000000000 --- a/tests/integration/bulkexports/v1/test_export_configuration.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding=utf-8 -r""" -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.bulkexports.v1.export_configuration("resource_type").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Configuration', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://bulkexports.twilio.com/v1/Exports/Calls/Configuration", - "enabled": true, - "webhook_url": "", - "webhook_method": "", - "resource_type": "Calls" - } - ''' - )) - - actual = self.client.bulkexports.v1.export_configuration("resource_type").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.bulkexports.v1.export_configuration("resource_type").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://bulkexports.twilio.com/v1/Exports/resource_type/Configuration', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://bulkexports.twilio.com/v1/Exports/Calls/Configuration", - "enabled": true, - "webhook_url": "", - "resource_type": "Calls", - "webhook_method": "" - } - ''' - )) - - actual = self.client.bulkexports.v1.export_configuration("resource_type").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/__init__.py b/tests/integration/chat/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/chat/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/chat/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/chat/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/chat/v1/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 507a029623..0000000000 --- a/tests/integration/chat/v1/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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 227354d559..0000000000 --- a/tests/integration/chat/v1/service/channel/test_member.py +++ /dev/null @@ -1,263 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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 c9fc815fc5..0000000000 --- a/tests/integration/chat/v1/service/channel/test_message.py +++ /dev/null @@ -1,273 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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 2fd1e8ff38..0000000000 --- a/tests/integration/chat/v1/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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 79a395e1d5..0000000000 --- a/tests/integration/chat/v1/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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 11f7730387..0000000000 --- a/tests/integration/chat/v1/service/test_user.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 c9fc143806..0000000000 --- a/tests/integration/chat/v1/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 43346e1777..0000000000 --- a/tests/integration/chat/v1/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 26e0d6dd1a..0000000000 --- a/tests/integration/chat/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.credentials("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("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 ee9f7a2791..0000000000 --- a/tests/integration/chat/v1/test_service.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -r""" -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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v1.services("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("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("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("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 c9fc143806..0000000000 --- a/tests/integration/chat/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/chat/v2/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/chat/v2/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 57e745c375..0000000000 --- a/tests/integration/chat/v2/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("INXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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 925b710825..0000000000 --- a/tests/integration/chat/v2/service/channel/test_member.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity", x_twilio_webhook_enabled="true") - - values = {'Identity': "identity", } - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - headers=headers, - )) - 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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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 3f7baced30..0000000000 --- a/tests/integration/chat/v2/service/channel/test_message.py +++ /dev/null @@ -1,386 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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": "fromUser", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/chat/v2/service/channel/test_webhook.py b/tests/integration/chat/v2/service/channel/test_webhook.py deleted file mode 100644 index 53dc8f8f2a..0000000000 --- a/tests/integration/chat/v2/service/channel/test_webhook.py +++ /dev/null @@ -1,287 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "webhook", - "configuration": { - "url": "dummy", - "method": "GET", - "filters": [ - "onMessageSent", - "onChannelDestroyed" - ], - "retry_count": 2 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "trigger", - "configuration": { - "url": "dummy", - "method": "POST", - "filters": [ - "keyword1", - "keyword2" - ], - "retry_count": 3 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [] - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(type="webhook") - - values = {'Type': "webhook", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "webhook", - "configuration": { - "url": "dummy", - "method": "GET", - "filters": [ - "onMessageSent", - "onChannelDestroyed" - ], - "retry_count": 2 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(type="webhook") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "trigger", - "configuration": { - "url": "dummy", - "method": "POST", - "filters": [ - "keyword1", - "keyword2" - ], - "retry_count": 3 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:51Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 91ec45500e..0000000000 --- a/tests/integration/chat/v2/service/test_binding.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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 acff8ee104..0000000000 --- a/tests/integration/chat/v2/service/test_channel.py +++ /dev/null @@ -1,265 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - headers=headers, - )) - - 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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services("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("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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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 09d918d765..0000000000 --- a/tests/integration/chat/v2/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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 0cde62f4f2..0000000000 --- a/tests/integration/chat/v2/service/test_user.py +++ /dev/null @@ -1,258 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity", x_twilio_webhook_enabled="true") - - values = {'Identity': "identity", } - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - headers=headers, - )) - 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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 c9fc143806..0000000000 --- a/tests/integration/chat/v2/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 d8d5594673..0000000000 --- a/tests/integration/chat/v2/service/user/test_user_binding.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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 23c80ad7f5..0000000000 --- a/tests/integration/chat/v2/service/user/test_user_channel.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "default", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "default", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_notification_level_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "muted", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_last_consumed_message_index_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 10, - "unread_messages_count": 5, - "notification_level": "muted", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - 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 8417231340..0000000000 --- a/tests/integration/chat/v2/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.credentials("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("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 9b8d4790d4..0000000000 --- a/tests/integration/chat/v2/test_service.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding=utf-8 -r""" -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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.chat.v2.services("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/conversations/__init__.py b/tests/integration/conversations/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/conversations/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/conversations/v1/__init__.py b/tests/integration/conversations/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/conversations/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/conversations/v1/conversation/__init__.py b/tests/integration/conversations/v1/conversation/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/conversations/v1/conversation/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/conversations/v1/conversation/message/__init__.py b/tests/integration/conversations/v1/conversation/message/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/conversations/v1/conversation/message/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/conversations/v1/conversation/message/test_delivery_receipt.py b/tests/integration/conversations/v1/conversation/message/test_delivery_receipt.py deleted file mode 100644 index b3c24983b1..0000000000 --- a/tests/integration/conversations/v1/conversation/message/test_delivery_receipt.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding=utf-8 -r""" -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 DeliveryReceiptTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .delivery_receipts("DYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Receipts/DYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_message_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "error_code": 3000, - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts/DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .delivery_receipts("DYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .delivery_receipts.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Receipts', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts?PageSize=50&Page=0", - "next_page_url": null, - "key": "delivery_receipts" - }, - "delivery_receipts": [ - { - "sid": "DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_message_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "error_code": 3000, - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts/DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "sid": "DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_message_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "error_code": 3000, - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts/DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "sid": "DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "message_sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_message_sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "failed", - "error_code": 3000, - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts/DYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .delivery_receipts.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/conversations/v1/conversation/test_message.py b/tests/integration/conversations/v1/conversation/test_message.py deleted file mode 100644 index 4fc58d2fa1..0000000000 --- a/tests/integration/conversations/v1/conversation/test_message.py +++ /dev/null @@ -1,354 +0,0 @@ -# coding=utf-8 -r""" -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.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - headers=headers, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": "Hello", - "media": null, - "author": "message author", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_create_with_media_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": null, - "media": [ - { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 42056, - "content_type": "image/jpeg", - "filename": "car.jpg" - } - ], - "author": "message author", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": "Hello", - "media": null, - "author": "message author", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": "Welcome!", - "media": null, - "author": "system", - "participant_sid": null, - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages?PageSize=50&Page=0", - "next_page_url": null, - "key": "messages" - }, - "messages": [ - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": "I like pie.", - "media": null, - "author": "pie_preferrer", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2016-03-24T20:37:57Z", - "date_updated": "2016-03-24T20:37:57Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - }, - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": "Cake is my favorite!", - "media": null, - "author": "cake_lover", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2016-03-24T20:38:21Z", - "date_updated": "2016-03-24T20:38:21Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - }, - { - "sid": "IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "body": null, - "media": [ - { - "sid": "MEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 42056, - "content_type": "image/jpeg", - "filename": "car.jpg" - } - ], - "author": "cake_lover", - "participant_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "attributes": "{ \\"importance\\": \\"high\\" }", - "date_created": "2016-03-24T20:38:21Z", - "date_updated": "2016-03-24T20:38:21Z", - "index": 0, - "delivery": { - "total": 2, - "sent": "all", - "delivered": "some", - "read": "some", - "failed": "none", - "undelivered": "none" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "delivery_receipts": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/IMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Receipts" - } - } - ] - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/conversations/v1/conversation/test_participant.py b/tests/integration/conversations/v1/conversation/test_participant.py deleted file mode 100644 index 01a05303d9..0000000000 --- a/tests/integration/conversations/v1/conversation/test_participant.py +++ /dev/null @@ -1,307 +0,0 @@ -# coding=utf-8 -r""" -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_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - headers=headers, - )) - - def test_create_sms_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "null", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "address": "+15558675310", - "proxy_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create() - - self.assertIsNotNone(actual) - - def test_create_chat_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "IDENTITY", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": null, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create() - - self.assertIsNotNone(actual) - - def test_create_gmms_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "IDENTITY", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "projected_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "null", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "address": "+15558675310", - "proxy_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_gmms_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "id", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "projected_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "null", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "address": "+15558675310", - "proxy_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?PageSize=50&Page=0", - "next_page_url": null, - "key": "participants" - }, - "participants": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "null", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": { - "type": "sms", - "address": "+15558675310", - "proxy_address": "+15017122661" - }, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "IDENTITY", - "attributes": "{ \\"role\\": \\"driver\\" }", - "messaging_binding": null, - "role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/conversations/v1/conversation/test_webhook.py b/tests/integration/conversations/v1/conversation/test_webhook.py deleted file mode 100644 index d77a87cca3..0000000000 --- a/tests/integration/conversations/v1/conversation/test_webhook.py +++ /dev/null @@ -1,266 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "webhook", - "configuration": { - "url": "https://example.com", - "method": "get", - "filters": [ - "onMessageSent", - "onConversationDestroyed" - ] - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "trigger", - "configuration": { - "url": "https://example.com", - "method": "post", - "filters": [ - "keyword1", - "keyword2" - ] - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [] - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(target="webhook") - - values = {'Target': "webhook", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "webhook", - "configuration": { - "url": "https://example.com", - "method": "get", - "filters": [ - "onMessageSent", - "onConversationDestroyed" - ] - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(target="webhook") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "conversation_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "target": "trigger", - "configuration": { - "url": "https://example.com", - "method": "post", - "filters": [ - "keyword1", - "keyword2" - ] - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:51Z", - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/conversations/v1/test_conversation.py b/tests/integration/conversations/v1/test_conversation.py deleted file mode 100644 index f9af69b97e..0000000000 --- a/tests/integration/conversations/v1/test_conversation.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -r""" -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 ConversationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations', - headers=headers, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "attributes": "{ \\"topic\\": \\"feedback\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "state": "inactive", - "timers": { - "date_inactive": "2015-12-16T22:19:38Z", - "date_closed": "2015-12-16T22:28:38Z" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "messages": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "webhooks": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations.create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "friendly_name": "friendly_name", - "attributes": "{ \\"topic\\": \\"feedback\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "state": "inactive", - "timers": { - "date_inactive": "2015-12-16T22:19:38Z", - "date_closed": "2015-12-16T22:28:38Z" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "messages": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "webhooks": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "My First Conversation", - "attributes": "{ \\"topic\\": \\"feedback\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "state": "active", - "timers": { - "date_inactive": "2015-12-16T22:19:38Z", - "date_closed": "2015-12-16T22:28:38Z" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "messages": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "webhooks": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.conversations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "conversations": [ - { - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Home Repair Visit", - "attributes": "{ \\"topic\\": \\"feedback\\" }", - "date_created": "2015-12-16T22:18:37Z", - "date_updated": "2015-12-16T22:18:38Z", - "state": "active", - "timers": { - "date_inactive": "2015-12-16T22:19:38Z", - "date_closed": "2015-12-16T22:28:38Z" - }, - "url": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "participants": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants", - "messages": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "webhooks": "https://conversations.twilio.com/v1/Conversations/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://conversations.twilio.com/v1/Conversations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://conversations.twilio.com/v1/Conversations?PageSize=50&Page=0", - "next_page_url": null, - "key": "conversations" - } - } - ''' - )) - - actual = self.client.conversations.v1.conversations.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/conversations/v1/test_webhook.py b/tests/integration/conversations/v1/test_webhook.py deleted file mode 100644 index 6fafefe148..0000000000 --- a/tests/integration/conversations/v1/test_webhook.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.webhooks().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://conversations.twilio.com/v1/Conversations/Webhooks', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "pre_webhook_url": "https://example.com/pre", - "post_webhook_url": "https://example.com/post", - "method": "GET", - "filters": [ - "onMessageSend", - "onConversationUpdated" - ], - "target": "webhook", - "url": "https://conversations.twilio.com/v1/Conversations/Webhooks" - } - ''' - )) - - actual = self.client.conversations.v1.webhooks().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.conversations.v1.webhooks().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://conversations.twilio.com/v1/Conversations/Webhooks', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "pre_webhook_url": "https://example.com/pre", - "post_webhook_url": "http://example.com/post", - "method": "GET", - "filters": [ - "onConversationUpdated" - ], - "target": "webhook", - "url": "https://conversations.twilio.com/v1/Conversations/Webhooks" - } - ''' - )) - - actual = self.client.conversations.v1.webhooks().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/fax/__init__.py b/tests/integration/fax/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/fax/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/fax/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/fax/v1/fax/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 332072f801..0000000000 --- a/tests/integration/fax/v1/fax/test_fax_media.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding=utf-8 -r""" -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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes("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("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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .media("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 29aff15f2a..0000000000 --- a/tests/integration/fax/v1/test_fax.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -r""" -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("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("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?DateCreatedOnOrBefore=2017-04-01T00%3A00%3A00Z&To=%2B14155554321&DateCreatedAfter=2017-03-31T00%3A00%3A00Z&From=%2B14155551234&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?DateCreatedOnOrBefore=2017-04-01T00%3A00%3A00Z&To=%2B14155554321&DateCreatedAfter=2017-03-31T00%3A00%3A00Z&From=%2B14155551234&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?To=%2B14155554321&From=%2B14155551234&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?To=%2B14155554321&From=%2B14155551234&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("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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.fax.v1.faxes("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("FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/flex_api/__init__.py b/tests/integration/flex_api/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/flex_api/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/flex_api/v1/__init__.py b/tests/integration/flex_api/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/flex_api/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/flex_api/v1/test_channel.py b/tests/integration/flex_api/v1/test_channel.py deleted file mode 100644 index e7132d9c86..0000000000 --- a/tests/integration/flex_api/v1/test_channel.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -r""" -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_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.channel.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/Channels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://flex-api.twilio.com/v1/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_chat_channels" - }, - "flex_chat_channels": [ - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.flex_api.v1.channel.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://flex-api.twilio.com/v1/Channels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/Channels?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_chat_channels" - }, - "flex_chat_channels": [] - } - ''' - )) - - actual = self.client.flex_api.v1.channel.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.channel.create(flex_flow_sid="FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", identity="identity", chat_user_friendly_name="chat_user_friendly_name", chat_friendly_name="chat_friendly_name") - - values = { - 'FlexFlowSid': "FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'Identity': "identity", - 'ChatUserFriendlyName': "chat_user_friendly_name", - 'ChatFriendlyName': "chat_friendly_name", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/Channels', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.channel.create(flex_flow_sid="FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", identity="identity", chat_user_friendly_name="chat_user_friendly_name", chat_friendly_name="chat_friendly_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://flex-api.twilio.com/v1/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.flex_api.v1.channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/flex_api/v1/test_configuration.py b/tests/integration/flex_api/v1/test_configuration.py deleted file mode 100644 index 1db6e681f7..0000000000 --- a/tests/integration/flex_api/v1/test_configuration.py +++ /dev/null @@ -1,546 +0,0 @@ -# coding=utf-8 -r""" -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 ConfigurationTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.configuration().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/Configuration', - )) - - 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", - "attributes": { - "main_attribute": "some_attribute" - }, - "status": "ok", - "taskrouter_workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_taskqueue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_taskqueues": [ - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "targettable": true - }, - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac", - "targettable": false - } - ], - "taskrouter_skills": [ - { - "name": "sales", - "multivalue": false, - "minimum": 0, - "maximum": 0 - }, - { - "name": "support", - "multivalue": true, - "minimum": 0, - "maximum": 10 - } - ], - "taskrouter_worker_channels": { - "agent": [ - { - "name": "default", - "availability": true, - "capacity": 1 - }, - { - "name": "voice", - "availability": false, - "capacity": 2 - } - ], - "supervisor": [ - { - "name": "default", - "availability": true, - "capacity": 2 - } - ] - }, - "taskrouter_worker_attributes": { - "agent": { - "region": "us-east" - }, - "supervisor": { - "region": "us" - } - }, - "taskrouter_offline_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "runtime_domain": "https://flex.twilio.com", - "messaging_service_instance_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flex_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ui_language": "en", - "ui_attributes": {}, - "ui_dependencies": {}, - "ui_version": "1.0", - "service_version": "1.0", - "call_recording_enabled": true, - "call_recording_webhook_url": "https://www.example.com/call-recording", - "crm_enabled": true, - "crm_type": "custom", - "crm_callback_url": "https://crm.com/a", - "crm_fallback_url": "https://crm.com/b", - "crm_attributes": { - "crm_attribute": "some_crm" - }, - "public_attributes": { - "public": "test" - }, - "plugin_service_enabled": true, - "plugin_service_attributes": { - "agent-logger": "^3.10.5", - "typewriter": "^7.0.1" - }, - "integrations": [ - { - "name": "twilio", - "type": "http", - "active": true, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "twilio-stage", - "type": "http", - "active": false, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}" - } - ], - "outbound_call_flows": { - "default": { - "caller_id": "+12345", - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "location": "EE", - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - }, - "queue_stats_configuration": { - "default": { - "service_level_threshold": 20, - "short_abandoned_threshold": 5, - "reset_timezone": "America/New_York", - "reset_time": "00:00" - }, - "queue_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reset_timezone": "Europe/Tallinn", - "reset_time": "01:00" - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "reset_timezone": "Europe/Paris", - "reset_time": "02:00" - } - ], - "queue_channel_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_level_threshold": 10, - "short_abandoned_threshold": 10 - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "service_level_threshold": 30, - "short_abandoned_threshold": 15 - } - ] - }, - "serverless_service_sids": [ - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "url": "https://flex-api.twilio.com/v1/Configuration" - } - ''' - )) - - actual = self.client.flex_api.v1.configuration().fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.configuration().create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/Configuration', - )) - - 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", - "attributes": { - "main_attribute": "some_attribute" - }, - "status": "ok", - "taskrouter_workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_taskqueue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_taskqueues": [ - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "targettable": true - }, - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac", - "targettable": false - } - ], - "taskrouter_skills": [ - { - "name": "sales", - "multivalue": false, - "minimum": 0, - "maximum": 0 - }, - { - "name": "support", - "multivalue": true, - "minimum": 0, - "maximum": 10 - } - ], - "taskrouter_worker_channels": { - "agent": [ - { - "name": "default", - "availability": true, - "capacity": 1 - }, - { - "name": "voice", - "availability": false, - "capacity": 2 - } - ], - "supervisor": [ - { - "name": "default", - "availability": true, - "capacity": 2 - } - ] - }, - "taskrouter_worker_attributes": { - "agent": { - "region": "us-east" - }, - "supervisor": { - "region": "us" - } - }, - "taskrouter_offline_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "runtime_domain": "https://flex.twilio.com", - "messaging_service_instance_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flex_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ui_language": "en", - "ui_attributes": {}, - "ui_dependencies": {}, - "ui_version": "1.0", - "service_version": "1.0", - "call_recording_enabled": true, - "call_recording_webhook_url": "https://www.example.com/call-recording", - "crm_enabled": true, - "crm_type": "custom", - "crm_callback_url": "https://crm.com/a", - "crm_fallback_url": "https://crm.com/b", - "crm_attributes": { - "crm_attribute": "some_crm" - }, - "public_attributes": { - "public": "test" - }, - "plugin_service_enabled": true, - "plugin_service_attributes": { - "agent-logger": "^3.10.5", - "typewriter": "^7.0.1" - }, - "integrations": [ - { - "name": "twilio", - "type": "http", - "active": true, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "twilio-stage", - "type": "http", - "active": false, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}" - } - ], - "outbound_call_flows": { - "default": { - "caller_id": "+12345", - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "location": "EE", - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - }, - "queue_stats_configuration": { - "default": { - "service_level_threshold": 20, - "short_abandoned_threshold": 5, - "reset_timezone": "America/New_York", - "reset_time": "00:00" - }, - "queue_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reset_timezone": "Europe/Tallinn", - "reset_time": "01:00" - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "reset_timezone": "Europe/Paris", - "reset_time": "02:00" - } - ], - "queue_channel_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_level_threshold": 10, - "short_abandoned_threshold": 10 - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "service_level_threshold": 30, - "short_abandoned_threshold": 15 - } - ] - }, - "serverless_service_sids": [ - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "url": "https://flex-api.twilio.com/v1/Configuration" - } - ''' - )) - - actual = self.client.flex_api.v1.configuration().create() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.configuration().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/Configuration', - )) - - 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", - "attributes": { - "main_attribute": "some_attribute" - }, - "status": "ok", - "taskrouter_workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_target_taskqueue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "taskrouter_taskqueues": [ - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "targettable": true - }, - { - "sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac", - "targettable": false - } - ], - "taskrouter_skills": [ - { - "name": "sales", - "multivalue": false, - "minimum": 0, - "maximum": 0 - }, - { - "name": "support", - "multivalue": true, - "minimum": 0, - "maximum": 10 - } - ], - "taskrouter_worker_channels": { - "agent": [ - { - "name": "default", - "availability": true, - "capacity": 1 - }, - { - "name": "voice", - "availability": false, - "capacity": 2 - } - ], - "supervisor": [ - { - "name": "default", - "availability": true, - "capacity": 2 - } - ] - }, - "taskrouter_worker_attributes": { - "agent": { - "region": "us-east" - }, - "supervisor": { - "region": "us" - } - }, - "taskrouter_offline_activity_sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "runtime_domain": "https://flex.twilio.com", - "messaging_service_instance_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "chat_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flex_service_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ui_language": "en", - "ui_attributes": {}, - "ui_dependencies": {}, - "ui_version": "1.0", - "service_version": "1.0", - "call_recording_enabled": true, - "call_recording_webhook_url": "https://www.example.com/call-recording", - "crm_enabled": true, - "crm_type": "custom", - "crm_callback_url": "https://crm.com/a", - "crm_fallback_url": "https://crm.com/b", - "crm_attributes": { - "crm_attribute": "some_crm" - }, - "public_attributes": { - "public": "test" - }, - "plugin_service_enabled": false, - "plugin_service_attributes": { - "agent-logger": "^3.10.5", - "typewriter": "^7.0.1" - }, - "integrations": [ - { - "name": "twilio", - "type": "http", - "active": true, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}", - "logo": "logo1", - "author": "somebody1" - }, - { - "name": "twilio-stage", - "type": "http", - "active": false, - "config": "{\\"callback\\":\\"twilio.com/cb\\",\\"allowed_methods\\":[\\"GET\\",\\"POST\\"]}" - } - ], - "outbound_call_flows": { - "default": { - "caller_id": "+12345", - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "location": "EE", - "workflow_sid": "WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - }, - "queue_stats_configuration": { - "default": { - "service_level_threshold": 20, - "short_abandoned_threshold": 5, - "reset_timezone": "America/New_York", - "reset_time": "00:00" - }, - "queue_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reset_timezone": "Europe/Tallinn", - "reset_time": "01:00" - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "reset_timezone": "Europe/Paris", - "reset_time": "02:00" - } - ], - "queue_channel_configurations": [ - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_level_threshold": 10, - "short_abandoned_threshold": 10 - }, - { - "queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "channel_sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "service_level_threshold": 30, - "short_abandoned_threshold": 15 - } - ] - }, - "serverless_service_sids": [ - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ZSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "url": "https://flex-api.twilio.com/v1/Configuration" - } - ''' - )) - - actual = self.client.flex_api.v1.configuration().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/flex_api/v1/test_flex_flow.py b/tests/integration/flex_api/v1/test_flex_flow.py deleted file mode 100644 index 1d9a9f1886..0000000000 --- a/tests/integration/flex_api/v1/test_flex_flow.py +++ /dev/null @@ -1,243 +0,0 @@ -# coding=utf-8 -r""" -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 FlexFlowTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.flex_flow.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/FlexFlows', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_flows" - }, - "flex_flows": [ - { - "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "friendly_name": "friendly_name", - "chat_service_sid": "SIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_type": "sms", - "contact_identity": "12345", - "enabled": true, - "integration_type": "studio", - "integration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "retry_count": 1 - }, - "long_lived": true, - "janitor_enabled": true, - "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.flex_api.v1.flex_flow.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://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_flows" - }, - "flex_flows": [] - } - ''' - )) - - actual = self.client.flex_api.v1.flex_flow.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "friendly_name": "friendly_name", - "chat_service_sid": "SIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_type": "sms", - "contact_identity": "12345", - "enabled": true, - "integration_type": "studio", - "integration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "retry_count": 1 - }, - "long_lived": true, - "janitor_enabled": true, - "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.flex_flow.create(friendly_name="friendly_name", chat_service_sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", channel_type="web") - - values = { - 'FriendlyName': "friendly_name", - 'ChatServiceSid': "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'ChannelType': "web", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/FlexFlows', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "friendly_name": "friendly_name", - "chat_service_sid": "SIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_type": "sms", - "contact_identity": "12345", - "enabled": true, - "integration_type": "studio", - "integration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "retry_count": 1 - }, - "long_lived": true, - "janitor_enabled": true, - "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.flex_flow.create(friendly_name="friendly_name", chat_service_sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", channel_type="web") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "friendly_name": "friendly_name", - "chat_service_sid": "SIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_type": "sms", - "contact_identity": "12345", - "enabled": true, - "integration_type": "studio", - "integration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "retry_count": 1 - }, - "long_lived": true, - "janitor_enabled": true, - "url": "https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://flex-api.twilio.com/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.flex_api.v1.flex_flow("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/flex_api/v1/test_web_channel.py b/tests/integration/flex_api/v1/test_web_channel.py deleted file mode 100644 index dcbb89fea9..0000000000 --- a/tests/integration/flex_api/v1/test_web_channel.py +++ /dev/null @@ -1,200 +0,0 @@ -# coding=utf-8 -r""" -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 WebChannelTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.web_channel.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/WebChannels', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://flex-api.twilio.com/v1/WebChannels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/WebChannels?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_chat_channels" - }, - "flex_chat_channels": [ - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/WebChannels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.flex_api.v1.web_channel.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://flex-api.twilio.com/v1/WebChannels?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://flex-api.twilio.com/v1/WebChannels?PageSize=50&Page=0", - "next_page_url": null, - "key": "flex_chat_channels" - }, - "flex_chat_channels": [] - } - ''' - )) - - actual = self.client.flex_api.v1.web_channel.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://flex-api.twilio.com/v1/WebChannels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/WebChannels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.web_channel.create(flex_flow_sid="FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", identity="identity", customer_friendly_name="customer_friendly_name", chat_friendly_name="chat_friendly_name") - - values = { - 'FlexFlowSid': "FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'Identity': "identity", - 'CustomerFriendlyName': "customer_friendly_name", - 'ChatFriendlyName': "chat_friendly_name", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/WebChannels', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/WebChannels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.web_channel.create(flex_flow_sid="FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", identity="identity", customer_friendly_name="customer_friendly_name", chat_friendly_name="chat_friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://flex-api.twilio.com/v1/WebChannels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "flex_flow_sid": "FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-08-01T22:10:40Z", - "date_updated": "2016-08-01T22:10:40Z", - "url": "https://flex-api.twilio.com/v1/WebChannels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://flex-api.twilio.com/v1/WebChannels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.flex_api.v1.web_channel("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/insights/__init__.py b/tests/integration/insights/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/insights/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/insights/v1/__init__.py b/tests/integration/insights/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/insights/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/insights/v1/call/__init__.py b/tests/integration/insights/v1/call/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/insights/v1/call/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/insights/v1/call/test_event.py b/tests/integration/insights/v1/call/test_event.py deleted file mode 100644 index 16faa4ef36..0000000000 --- a/tests/integration/insights/v1/call/test_event.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Events', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "events", - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0" - }, - "events": [ - { - "timestamp": "2019-09-19T22:15:23Z", - "call_sid": "CA03a02b156c6faa96c86906f7e9ad0f38", - "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", - "edge": "sdk_edge", - "group": "connection", - "name": "error", - "level": "ERROR", - "sdk_edge": { - "error": { - "code": 31600 - }, - "metadata": { - "client_name": "GTI9300323095d271b890c91568931321395", - "location": { - "lat": 37.4192, - "lon": -122.0574 - }, - "city": "Mountain View", - "country_code": "US", - "country_subdivision": "California", - "ip_address": "108.177.7.83", - "sdk": { - "type": "twilio-voice-android", - "version": "4.5.1", - "platform": "android", - "selected_region": "gll", - "os": { - "name": "android", - "version": "4.3" - }, - "device": { - "model": "GT-I9300", - "type": "GT-I9300", - "vendor": "samsung", - "arch": "armeabi-v7a" - } - } - } - }, - "client_edge": null, - "carrier_edge": null, - "sip_edge": null - } - ] - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.assertIsNotNone(actual) - - def test_read_deep_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 10, - "page_size": 5, - "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=5&Page=0", - "previous_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=5&Page=9&PageToken=DP10", - "next_page_url": null, - "key": "events", - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=5&Page=10" - }, - "events": [ - { - "timestamp": "2019-09-19T22:15:23Z", - "call_sid": "CA03a02b156c6faa96c86906f7e9ad0f38", - "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", - "edge": "sdk_edge", - "group": "connection", - "name": "error", - "level": "ERROR", - "sdk_edge": { - "error": { - "code": 31600 - }, - "metadata": { - "client_name": "GTI9300323095d271b890c91568931321395", - "location": { - "lat": 37.4192, - "lon": -122.0574 - }, - "city": "Mountain View", - "country_code": "US", - "country_subdivision": "California", - "ip_address": "108.177.7.83", - "sdk": { - "type": "twilio-voice-android", - "version": "4.5.1", - "platform": "android", - "selected_region": "gll", - "os": { - "name": "android", - "version": "4.3" - }, - "device": { - "model": "GT-I9300", - "type": "GT-I9300", - "vendor": "samsung", - "arch": "armeabi-v7a" - } - } - } - }, - "client_edge": null, - "carrier_edge": null, - "sip_edge": null - } - ] - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/insights/v1/call/test_metric.py b/tests/integration/insights/v1/call/test_metric.py deleted file mode 100644 index 2c1954fa42..0000000000 --- a/tests/integration/insights/v1/call/test_metric.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding=utf-8 -r""" -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 MetricTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .metrics.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Metrics', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "metrics", - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0" - }, - "metrics": [ - { - "timestamp": "2019-10-07T22:32:06Z", - "call_sid": "CA7569efe0253644fa4a88aa97beca3310", - "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", - "edge": "sdk_edge", - "direction": "both", - "sdk_edge": { - "interval": { - "packets_received": 50, - "packets_lost": 0, - "audio_in": { - "value": 81.0 - }, - "audio_out": { - "value": 5237.0 - }, - "jitter": { - "value": 9 - }, - "mos": { - "value": 4.39 - }, - "rtt": { - "value": 81 - } - }, - "cumulative": { - "bytes_received": 547788, - "bytes_sent": 329425, - "packets_received": 3900, - "packets_lost": 0, - "packets_sent": 3934 - } - }, - "client_edge": null, - "carrier_edge": null, - "sip_edge": null - } - ] - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .metrics.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 10, - "page_size": 5, - "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=0", - "previous_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=9&PageToken=DP10", - "next_page_url": null, - "key": "metrics", - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=10" - }, - "metrics": [ - { - "timestamp": "2019-10-07T22:32:06Z", - "call_sid": "CA7569efe0253644fa4a88aa97beca3310", - "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", - "edge": "sdk_edge", - "direction": "both", - "sdk_edge": { - "interval": { - "packets_received": 50, - "packets_lost": 0, - "audio_in": { - "value": 81.0 - }, - "audio_out": { - "value": 5237.0 - }, - "jitter": { - "value": 9 - }, - "mos": { - "value": 4.39 - }, - "rtt": { - "value": 81 - } - }, - "cumulative": { - "bytes_received": 547788, - "bytes_sent": 329425, - "packets_received": 3900, - "packets_lost": 0, - "packets_sent": 3934 - } - }, - "client_edge": null, - "carrier_edge": null, - "sip_edge": null - } - ] - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .metrics.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/insights/v1/call/test_summary.py b/tests/integration/insights/v1/call/test_summary.py deleted file mode 100644 index b6aca2351c..0000000000 --- a/tests/integration/insights/v1/call/test_summary.py +++ /dev/null @@ -1,62 +0,0 @@ -# coding=utf-8 -r""" -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 CallSummaryTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .summary().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Summary', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_type": "carrier", - "call_state": "ringing", - "processing_state": "complete", - "start_time": "2015-07-30T20:00:00Z", - "end_time": "2015-07-30T20:00:00Z", - "duration": 100, - "connect_duration": 99, - "from": {}, - "to": {}, - "carrier_edge": {}, - "client_edge": {}, - "sdk_edge": {}, - "sip_edge": {}, - "tags": [ - "tags" - ], - "attributes": {}, - "properties": {}, - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Summary" - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .summary().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/insights/v1/test_call.py b/tests/integration/insights/v1/test_call.py deleted file mode 100644 index db2eb37d2d..0000000000 --- a/tests/integration/insights/v1/test_call.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "events": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events", - "metrics": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics", - "summary": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Summary" - } - } - ''' - )) - - actual = self.client.insights.v1.calls("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/__init__.py b/tests/integration/ip_messaging/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/ip_messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 0f344db4f5..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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 8d1078bbac..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_member.py +++ /dev/null @@ -1,263 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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 008ac4ce59..0000000000 --- a/tests/integration/ip_messaging/v1/service/channel/test_message.py +++ /dev/null @@ -1,273 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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 4313ccd606..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_channel.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("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.ip_messaging.v1.services("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("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.ip_messaging.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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 62cafb4df9..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("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.ip_messaging.v1.services("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("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.ip_messaging.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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 4806a22526..0000000000 --- a/tests/integration/ip_messaging/v1/service/test_user.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("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.ip_messaging.v1.services("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("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.ip_messaging.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v1/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 1bcd732408..0000000000 --- a/tests/integration/ip_messaging/v1/service/user/test_user_channel.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 bd7167710d..0000000000 --- a/tests/integration/ip_messaging/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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://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.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://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.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("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.ip_messaging.v1.credentials("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("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.ip_messaging.v1.credentials("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("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.ip_messaging.v1.credentials("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 7663102736..0000000000 --- a/tests/integration/ip_messaging/v1/test_service.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -r""" -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("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.ip_messaging.v1.services("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("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.ip_messaging.v1.services("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://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.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://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.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("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.ip_messaging.v1.services("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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v2/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 95d0f52c75..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_invite.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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?Identity=identity&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?Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .invites("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 15db2a6bdd..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_member.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members.create(identity="identity", x_twilio_webhook_enabled="true") - - values = {'Identity': "identity", } - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members', - headers=headers, - )) - 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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Members/MBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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", - "attributes": "{}", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .members("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 2a477277f3..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_message.py +++ /dev/null @@ -1,386 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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": "fromUser", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messages("IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/ip_messaging/v2/service/channel/test_webhook.py b/tests/integration/ip_messaging/v2/service/channel/test_webhook.py deleted file mode 100644 index 8a58c65ea3..0000000000 --- a/tests/integration/ip_messaging/v2/service/channel/test_webhook.py +++ /dev/null @@ -1,287 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "webhook", - "configuration": { - "url": "dummy", - "method": "GET", - "filters": [ - "onMessageSent", - "onChannelDestroyed" - ], - "retry_count": 2 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "trigger", - "configuration": { - "url": "dummy", - "method": "POST", - "filters": [ - "keyword1", - "keyword2" - ], - "retry_count": 3 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 5, - "first_page_url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=5&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "webhooks" - }, - "webhooks": [] - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "studio", - "configuration": { - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(type="webhook") - - values = {'Type': "webhook", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "webhook", - "configuration": { - "url": "dummy", - "method": "GET", - "filters": [ - "onMessageSent", - "onChannelDestroyed" - ], - "retry_count": 2 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:50Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(type="webhook") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "type": "trigger", - "configuration": { - "url": "dummy", - "method": "POST", - "filters": [ - "keyword1", - "keyword2" - ], - "retry_count": 3 - }, - "date_created": "2016-03-24T21:05:50Z", - "date_updated": "2016-03-24T21:05:51Z", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/WHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("WHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 e91c976d99..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_binding.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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("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.ip_messaging.v2.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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 cee6f2852c..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_channel.py +++ /dev/null @@ -1,265 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - headers=headers, - )) - - 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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("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("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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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", - "webhooks": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "last_message": null - } - } - ''' - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels("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 5bc4e8bbb6..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_role.py +++ /dev/null @@ -1,246 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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("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.ip_messaging.v2.services("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("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.ip_messaging.v2.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .roles("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 f1db0f74bb..0000000000 --- a/tests/integration/ip_messaging/v2/service/test_user.py +++ /dev/null @@ -1,258 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users.create(identity="identity", x_twilio_webhook_enabled="true") - - values = {'Identity': "identity", } - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users', - headers=headers, - )) - 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.ip_messaging.v2.services("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("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.ip_messaging.v2.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(x_twilio_webhook_enabled="true") - - headers = {'X-Twilio-Webhook-Enabled': "true", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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 c9fc143806..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 99614e7c90..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/test_user_binding.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_bindings("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 02d8c6adb8..0000000000 --- a/tests/integration/ip_messaging/v2/service/user/test_user_channel.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "default", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "default", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Users/USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels/CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_notification_level_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 5, - "unread_messages_count": 5, - "notification_level": "muted", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_last_consumed_message_index_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_sid": "CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user_sid": "USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "member_sid": "MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "joined", - "last_consumed_message_index": 10, - "unread_messages_count": 5, - "notification_level": "muted", - "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .users("USXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .user_channels("CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - 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 ac9391c8c7..0000000000 --- a/tests/integration/ip_messaging/v2/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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://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.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://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.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("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.ip_messaging.v2.credentials("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("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.ip_messaging.v2.credentials("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("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.ip_messaging.v2.credentials("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 dee7fab70c..0000000000 --- a/tests/integration/ip_messaging/v2/test_service.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding=utf-8 -r""" -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("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.ip_messaging.v2.services("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("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.ip_messaging.v2.services("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://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.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://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.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("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.ip_messaging.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/lookups/__init__.py b/tests/integration/lookups/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/lookups/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/lookups/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 cb0d1ccd45..0000000000 --- a/tests/integration/lookups/v1/test_phone_number.py +++ /dev/null @@ -1,329 +0,0 @@ -# coding=utf-8 -r""" -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("+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": null, - "carrier": null, - "fraud": null, - "add_ons": null, - "country_code": "US", - "national_format": "(510) 867-5310", - "phone_number": "+15108675310", - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+15108675310" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_carrier_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": null, - "carrier": { - "error_code": null, - "mobile_country_code": "310", - "mobile_network_code": "456", - "name": "verizon", - "type": "mobile" - }, - "country_code": "US", - "national_format": "(510) 867-5310", - "phone_number": "+15108675310", - "fraud": null, - "add_ons": null, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+15108675310?Type=carrier" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_carrier_international_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": null, - "carrier": { - "error_code": null, - "mobile_country_code": null, - "mobile_network_code": null, - "name": "Vodafone Business Solutions", - "type": "landline" - }, - "country_code": "GB", - "national_format": "020 7765 1182", - "phone_number": "+4402077651182", - "fraud": null, - "add_ons": null, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+4402077651182?Type=carrier" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_caller_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": { - "caller_name": "Delicious Cheese Cake", - "caller_type": "CONSUMER", - "error_code": null - }, - "carrier": null, - "fraud": null, - "country_code": "US", - "national_format": "(510) 867-5310", - "phone_number": "+15108675310", - "add_ons": null, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+15108675310?Type=caller-name" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_carrier_and_caller_name_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" - }, - "fraud": null, - "country_code": "US", - "national_format": "(510) 867-5310", - "phone_number": "+15108675310", - "add_ons": { - "status": "successful", - "message": null, - "code": null, - "results": {} - }, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+15108675310?Type=carrier&Type=caller-name" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_addons_whitepages_pro_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": { - "caller_name": "EMPIRE STATE BUILDING", - "caller_type": "BUSINESS", - "error_code": null - }, - "country_code": "US", - "phone_number": "+12127363100", - "national_format": "(212) 736-3100", - "carrier": null, - "fraud": null, - "add_ons": { - "status": "successful", - "message": null, - "code": null, - "results": { - "whitepages_pro_caller_id": { - "status": "successful", - "request_sid": "XR28b8f152ae12345605b0b3cc34123456", - "message": null, - "code": null, - "result": { - "phone_number": "2127363100", - "warnings": [], - "historical_addresses": [], - "alternate_phones": [], - "error": null, - "is_commercial": true, - "associated_people": [], - "country_calling_code": "1", - "belongs_to": [], - "is_valid": true, - "line_type": "NonFixedVOIP", - "carrier": "Level 3 Communications", - "current_addresses": [ - { - "city": "New York", - "lat_long": { - "latitude": 40.748731, - "longitude": -73.986413, - "accuracy": "RoofTop" - }, - "is_active": null, - "location_type": "Address", - "street_line_2": null, - "link_to_person_start_date": "2018-08-28", - "street_line_1": "350 5th Ave", - "postal_code": "10118", - "delivery_point": "MultiUnit", - "country_code": "US", - "state_code": "NY", - "id": "Location.4e81b857-1234-5678-31d29a3301e1", - "zip4": "0110" - } - ], - "id": "Phone.f8396fef-1234-5678-bc7128b6fd99", - "is_prepaid": false - } - } - } - }, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+12127363100?Type=caller-name" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_addons_nomorobo_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": null, - "country_code": "US", - "phone_number": "+19892008374", - "national_format": "(989) 200-8374", - "carrier": { - "mobile_country_code": "310", - "mobile_network_code": null, - "name": "Ytel/Blitz", - "type": "mobile", - "error_code": null - }, - "fraud": null, - "add_ons": { - "status": "successful", - "message": null, - "code": null, - "results": { - "nomorobo_spamscore": { - "status": "successful", - "request_sid": "XR763c8acc4c56d5e3e18d2f0f12345bc1", - "message": null, - "code": null, - "result": { - "status": "success", - "message": "success", - "score": 1 - } - } - } - }, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+19892008374?Type=carrier" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_addons_payfone_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "caller_name": null, - "country_code": "US", - "phone_number": "+16502530000", - "national_format": "(650) 253-0000", - "carrier": { - "mobile_country_code": null, - "mobile_network_code": null, - "name": "Level 3 Communications, LLC", - "type": "landline", - "error_code": null - }, - "fraud": null, - "add_ons": { - "status": "successful", - "message": null, - "code": null, - "results": { - "payfone_tcpa_compliance": { - "status": "successful", - "request_sid": "XRd3a2991c9108bde3ca9589ed84d31463", - "message": null, - "code": null, - "result": { - "Status": 0, - "Response": { - "MSISDNType": "NonFixedVoIP", - "NumberMatch": "I", - "VerifyNumberTransactionId": "2019459819" - }, - "RequestId": "XRd3a2991c9108bde3ca9589ed84d31463", - "Description": "Success." - } - } - } - }, - "url": "https://lookups.twilio.com/v1/PhoneNumbers/+16502530000?Type=carrier" - } - ''' - )) - - actual = self.client.lookups.v1.phone_numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/messaging/__init__.py b/tests/integration/messaging/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/messaging/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/messaging/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 478fb218e5..0000000000 --- a/tests/integration/messaging/v1/service/test_alpha_sender.py +++ /dev/null @@ -1,162 +0,0 @@ -# coding=utf-8 -r""" -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("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("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("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AlphaSenders/AIaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders("AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .alpha_senders("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 da57c2cbb1..0000000000 --- a/tests/integration/messaging/v1/service/test_phone_number.py +++ /dev/null @@ -1,186 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services("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("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("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 2b0f1f19c3..0000000000 --- a/tests/integration/messaging/v1/service/test_short_code.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.messaging.v1.services("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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": [ - "SMS" - ], - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ShortCodes/SCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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 a004865f26..0000000000 --- a/tests/integration/messaging/v1/test_service.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -r""" -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", - "messages": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "broadcasts": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Broadcasts" - }, - "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("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", - "messages": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "broadcasts": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Broadcasts" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("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", - "messages": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "broadcasts": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Broadcasts" - }, - "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("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", - "messages": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", - "broadcasts": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Broadcasts" - }, - "url": "https://messaging.twilio.com/v1/Services/MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.messaging.v1.services("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.messaging.v1.services("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("MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/monitor/__init__.py b/tests/integration/monitor/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/monitor/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/monitor/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 7d9a03cdbf..0000000000 --- a/tests/integration/monitor/v1/test_alert.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "request_headers": "request_headers", - "sid": "NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://monitor.twilio.com/v1/Alerts/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "PNe2cd757cd5257b0217a447933a0290d2" - } - ''' - )) - - actual = self.client.monitor.v1.alerts("NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(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?LogLevel=log_level&StartDate=2016-01-01&EndDate=2016-01-01&PageSize=50&Page=0", - "key": "alerts", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Alerts?LogLevel=log_level&StartDate=2016-01-01&EndDate=2016-01-01&PageSize=50&Page=0" - } - } - ''' - )) - - 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": "https://monitor.twilio.com/v1/Alerts/NOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "PNe2cd757cd5257b0217a447933a0290d2" - } - ], - "meta": { - "first_page_url": "https://monitor.twilio.com/v1/Alerts?LogLevel=log_level&StartDate=2016-01-01&EndDate=2016-01-01&PageSize=50&Page=0", - "key": "alerts", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://monitor.twilio.com/v1/Alerts?LogLevel=log_level&StartDate=2016-01-01&EndDate=2016-01-01&PageSize=50&Page=0" - } - } - ''' - )) - - 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 7309e1decd..0000000000 --- a/tests/integration/monitor/v1/test_event.py +++ /dev/null @@ -1,143 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 c9fc143806..0000000000 --- a/tests/integration/notify/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/notify/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/notify/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 20e21915b0..0000000000 --- a/tests/integration/notify/v1/service/test_binding.py +++ /dev/null @@ -1,210 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .bindings("BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services("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("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("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?Tag=tag&Identity=identity&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?Tag=tag&Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services("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?Tag=tag&Identity=identity&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?Tag=tag&Identity=identity&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.notify.v1.services("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 6359531634..0000000000 --- a/tests/integration/notify/v1/service/test_notification.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .notifications.create() - - 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 f65f3db777..0000000000 --- a/tests/integration/notify/v1/test_credential.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials("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("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.credentials("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("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 f998f5b527..0000000000 --- a/tests/integration/notify/v1/test_service.py +++ /dev/null @@ -1,272 +0,0 @@ -# coding=utf-8 -r""" -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", - "delivery_callback_url": "Hello", - "delivery_callback_enabled": true, - "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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.notify.v1.services("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", - "delivery_callback_url": "Hello", - "delivery_callback_enabled": true, - "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("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", - "delivery_callback_url": "Hello", - "delivery_callback_enabled": true, - "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("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", - "delivery_callback_url": "Hello", - "delivery_callback_enabled": true, - "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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/__init__.py b/tests/integration/numbers/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/numbers/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/numbers/v2/__init__.py b/tests/integration/numbers/v2/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/numbers/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/numbers/v2/regulatory_compliance/__init__.py b/tests/integration/numbers/v2/regulatory_compliance/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/numbers/v2/regulatory_compliance/bundle/__init__.py b/tests/integration/numbers/v2/regulatory_compliance/bundle/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/bundle/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/numbers/v2/regulatory_compliance/bundle/test_evaluation.py b/tests/integration/numbers/v2/regulatory_compliance/bundle/test_evaluation.py deleted file mode 100644 index 8714214508..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/bundle/test_evaluation.py +++ /dev/null @@ -1,611 +0,0 @@ -# coding=utf-8 -r""" -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 EvaluationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "noncompliant", - "date_created": "2020-04-28T18:14:01Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": [ - { - "friendly_name": "Business", - "object_type": "business", - "passed": false, - "failure_reason": "A Business End-User is missing. Please add one to the regulatory bundle.", - "error_code": 22214, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Please enter in a Business Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Business Registration Number", - "object_field": "business_registration_number", - "failure_reason": "The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Please enter in a First Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Please enter in a Last Name on the Business information.", - "error_code": 22215 - } - ], - "requirement_friendly_name": "Business", - "requirement_name": "business_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Name", - "requirement_name": "business_name_info" - }, - { - "friendly_name": "Excerpt from the commercial register showing French address", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Address sid(s)", - "object_field": "address_sids", - "failure_reason": "The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.", - "error_code": 22219 - } - ], - "requirement_friendly_name": "Business Address (Proof of Address)", - "requirement_name": "business_address_proof_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis)", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Document Number", - "object_field": "document_number", - "failure_reason": "The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Registration Number", - "requirement_name": "business_reg_no_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Authorized Representative", - "requirement_name": "name_of_auth_rep_info" - }, - { - "friendly_name": "Executed Copy of Power of Attorney", - "object_type": "power_of_attorney", - "passed": false, - "failure_reason": "An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [], - "requirement_friendly_name": "Power of Attorney", - "requirement_name": "power_of_attorney_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing on the Governnment-Issued ID.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing on the Government-issued ID", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Person granted the Power of Attorney", - "requirement_name": "name_in_power_of_attorney_info" - } - ] - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations.create() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "noncompliant", - "date_created": "2020-04-28T18:14:01Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": [ - { - "friendly_name": "Business", - "object_type": "business", - "passed": false, - "failure_reason": "A Business End-User is missing. Please add one to the regulatory bundle.", - "error_code": 22214, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Please enter in a Business Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Business Registration Number", - "object_field": "business_registration_number", - "failure_reason": "The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Please enter in a First Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Please enter in a Last Name on the Business information.", - "error_code": 22215 - } - ], - "requirement_friendly_name": "Business", - "requirement_name": "business_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Name", - "requirement_name": "business_name_info" - }, - { - "friendly_name": "Excerpt from the commercial register showing French address", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Address sid(s)", - "object_field": "address_sids", - "failure_reason": "The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.", - "error_code": 22219 - } - ], - "requirement_friendly_name": "Business Address (Proof of Address)", - "requirement_name": "business_address_proof_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis)", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Document Number", - "object_field": "document_number", - "failure_reason": "The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Registration Number", - "requirement_name": "business_reg_no_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Authorized Representative", - "requirement_name": "name_of_auth_rep_info" - }, - { - "friendly_name": "Executed Copy of Power of Attorney", - "object_type": "power_of_attorney", - "passed": false, - "failure_reason": "An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [], - "requirement_friendly_name": "Power of Attorney", - "requirement_name": "power_of_attorney_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing on the Governnment-Issued ID.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing on the Government-issued ID", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Person granted the Power of Attorney", - "requirement_name": "name_in_power_of_attorney_info" - } - ] - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations("ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Evaluations/ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "noncompliant", - "date_created": "2020-04-28T18:14:01Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations/ELaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "results": [ - { - "friendly_name": "Business", - "object_type": "business", - "passed": false, - "failure_reason": "A Business End-User is missing. Please add one to the regulatory bundle.", - "error_code": 22214, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Please enter in a Business Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Business Registration Number", - "object_field": "business_registration_number", - "failure_reason": "The Business Registration Number is missing. Please enter in a Business Registration Number on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Please enter in a First Name on the Business information.", - "error_code": 22215 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Please enter in a Last Name on the Business information.", - "error_code": 22215 - } - ], - "requirement_friendly_name": "Business", - "requirement_name": "business_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Business Name", - "object_field": "business_name", - "failure_reason": "The Business Name is missing. Or, it does not match the Business Name you entered within Business information. Please enter in the Business Name shown on the Excerpt from the commercial register (Extrait K-bis) showing name of Authorized Representative or make sure both Business Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Name", - "requirement_name": "business_name_info" - }, - { - "friendly_name": "Excerpt from the commercial register showing French address", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register showing French address is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Address sid(s)", - "object_field": "address_sids", - "failure_reason": "The Address is missing. Please enter in the address shown on the Excerpt from the commercial register showing French address.", - "error_code": 22219 - } - ], - "requirement_friendly_name": "Business Address (Proof of Address)", - "requirement_name": "business_address_proof_info" - }, - { - "friendly_name": "Excerpt from the commercial register (Extrait K-bis)", - "object_type": "commercial_registrar_excerpt", - "passed": false, - "failure_reason": "An Excerpt from the commercial register (Extrait K-bis) is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "Document Number", - "object_field": "document_number", - "failure_reason": "The Document Number is missing. Please enter in the Document Number shown on the Excerpt from the commercial register (Extrait K-bis).", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Business Registration Number", - "requirement_name": "business_reg_no_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing. Or, it does not match the First Name you entered within Business information. Please enter in the First Name shown on the Government-issued ID or make sure both First Name fields use the same exact inputs.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing. Or, it does not match the Last Name you entered within Business information. Please enter in the Last Name shown on the Government-issued ID or make sure both Last Name fields use the same exact inputs.", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Authorized Representative", - "requirement_name": "name_of_auth_rep_info" - }, - { - "friendly_name": "Executed Copy of Power of Attorney", - "object_type": "power_of_attorney", - "passed": false, - "failure_reason": "An Executed Copy of Power of Attorney is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [], - "requirement_friendly_name": "Power of Attorney", - "requirement_name": "power_of_attorney_info" - }, - { - "friendly_name": "Government-issued ID", - "object_type": "government_issued_document", - "passed": false, - "failure_reason": "A Government-issued ID is missing. Please add one to the regulatory bundle.", - "error_code": 22216, - "valid": [], - "invalid": [ - { - "friendly_name": "First Name", - "object_field": "first_name", - "failure_reason": "The First Name is missing on the Governnment-Issued ID.", - "error_code": 22217 - }, - { - "friendly_name": "Last Name", - "object_field": "last_name", - "failure_reason": "The Last Name is missing on the Government-issued ID", - "error_code": 22217 - } - ], - "requirement_friendly_name": "Name of Person granted the Power of Attorney", - "requirement_name": "name_in_power_of_attorney_info" - } - ] - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .evaluations("ELXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/bundle/test_item_assignment.py b/tests/integration/numbers/v2/regulatory_compliance/bundle/test_item_assignment.py deleted file mode 100644 index 9b4ee8286f..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/bundle/test_item_assignment.py +++ /dev/null @@ -1,183 +0,0 @@ -# coding=utf-8 -r""" -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 ItemAssignmentTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments.create(object_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'ObjectSid': "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ItemAssignments', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2019-07-31T02:34:41Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments.create(object_sid="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ItemAssignments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2019-07-31T02:34:41Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ItemAssignments/BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bundle_sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "object_sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2019-07-31T02:34:41Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments/BVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ItemAssignments/BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .item_assignments("BVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_bundle.py b/tests/integration/numbers/v2/regulatory_compliance/test_bundle.py deleted file mode 100644 index 6901ddb107..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_bundle.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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 BundleTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles.create(friendly_name="friendly_name", email="email") - - values = {'FriendlyName': "friendly_name", 'Email': "email", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "status": "draft", - "email": "email", - "status_callback": "http://www.example.com", - "valid_until": null, - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "evaluations": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations", - "item_assignments": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles.create(friendly_name="friendly_name", email="email") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "status": "provisionally-approved", - "email": "email", - "status_callback": "http://www.example.com", - "valid_until": "2020-07-31T01:00:00Z", - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "evaluations": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations", - "item_assignments": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles?Status=draft&RegulationSid=RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&IsoCountry=US&FriendlyName=friendly_name&NumberType=mobile&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles?Status=draft&RegulationSid=RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&IsoCountry=US&FriendlyName=friendly_name&NumberType=mobile&PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "status": "draft", - "valid_until": null, - "email": "email", - "status_callback": "http://www.example.com", - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "evaluations": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations", - "item_assignments": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "regulation_sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "status": "draft", - "email": "email", - "status_callback": "http://www.example.com", - "valid_until": null, - "date_created": "2019-07-30T22:29:24Z", - "date_updated": "2019-07-31T01:09:00Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "evaluations": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Evaluations", - "item_assignments": "https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ItemAssignments" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Bundles/BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .bundles("BUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_end_user.py b/tests/integration/numbers/v2/regulatory_compliance/test_end_user.py deleted file mode 100644 index f8e3cfeb55..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_end_user.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding=utf-8 -r""" -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 EndUserTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_users.create(friendly_name="friendly_name", type="individual") - - values = {'FriendlyName': "friendly_name", 'Type': "individual", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "type": "individual", - "attributes": { - "email": "foobar@twilio.com" - }, - "date_created": "2019-07-30T21:57:45Z", - "date_updated": "2019-07-30T21:57:45Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_users.create(friendly_name="friendly_name", type="individual") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_users.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_users.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "type": "individual", - "attributes": { - "email": "foobar@twilio.com" - }, - "date_created": "2019-07-30T21:57:45Z", - "date_updated": "2019-07-30T21:57:45Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_users.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_users("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "type": "individual", - "attributes": { - "email": "foobar@twilio.com" - }, - "date_created": "2019-07-30T21:57:45Z", - "date_updated": "2019-07-30T21:57:45Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_users("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_users("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "type": "individual", - "attributes": { - "email": "foobar@twilio.com" - }, - "date_created": "2019-07-30T21:57:45Z", - "date_updated": "2019-07-30T21:57:45Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_users("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_end_user_type.py b/tests/integration/numbers/v2/regulatory_compliance/test_end_user_type.py deleted file mode 100644 index efa9cd99b9..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_end_user_type.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -r""" -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 EndUserTypeTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_user_types.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end_user_types": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes?PageSize=50&Page=0", - "next_page_url": null, - "key": "end_user_types" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_user_types.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "end_user_types": [ - { - "sid": "OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "machine_name": "machine_name", - "fields": [ - { - "friendly_name": "Business Purpose", - "machine_name": "business_purpose", - "constraint": "String" - }, - { - "friendly_name": "Last Name", - "machine_name": "last_name", - "constraint": "String" - } - ], - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes/OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes?PageSize=50&Page=0", - "next_page_url": null, - "key": "end_user_types" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_user_types.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .end_user_types("OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes/OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "machine_name": "machine_name", - "fields": [ - { - "friendly_name": "Business Purpose", - "machine_name": "business_purpose", - "constraint": "String" - }, - { - "friendly_name": "Last Name", - "machine_name": "last_name", - "constraint": "String" - } - ], - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/EndUserTypes/OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .end_user_types("OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_regulation.py b/tests/integration/numbers/v2/regulatory_compliance/test_regulation.py deleted file mode 100644 index fb1433eb98..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_regulation.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -r""" -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 RegulationTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .regulations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations?IsoCountry=US&EndUserType=business&NumberType=mobile&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations?IsoCountry=US&EndUserType=business&NumberType=mobile&PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .regulations.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Australia: Local - Individual", - "iso_country": "AU", - "number_type": "local", - "end_user_type": "individual", - "requirements": { - "end_user": [ - { - "name": "Individual", - "type": "individual", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations/individual", - "fields": [ - "first_name", - "last_name" - ] - } - ], - "supporting_document": [ - [ - { - "name": "Address", - "type": "document", - "description": "The physical location of the individual or business. Must be within locality or region covered by the phone numbers prefix; a PO Box is not acceptable where a local address is required.", - "accepted_documents": [ - { - "name": "Address Validation", - "type": "address", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/DocumentTypes/address", - "fields": [] - } - ] - } - ] - ] - }, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations/RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .regulations.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .regulations("RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations/RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Australia: Local - Individual", - "iso_country": "AU", - "number_type": "local", - "end_user_type": "individual", - "requirements": { - "end_user": [ - { - "name": "Individual", - "type": "individual", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations/individual", - "fields": [ - "first_name", - "last_name" - ] - } - ], - "supporting_document": [ - [ - { - "name": "Address", - "type": "document", - "description": "The physical location of the individual or business. Must be within locality or region covered by the phone numbers prefix; a PO Box is not acceptable where a local address is required.", - "accepted_documents": [ - { - "name": "Address Validation", - "type": "address", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/DocumentTypes/address", - "fields": [] - } - ] - } - ] - ] - }, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/Regulations/RNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .regulations("RNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document.py b/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document.py deleted file mode 100644 index 25ff824d39..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding=utf-8 -r""" -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 SupportingDocumentTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_documents.create(friendly_name="friendly_name", type="type") - - values = {'FriendlyName': "friendly_name", 'Type': "type", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "mime_type": "mime_type", - "status": "draft", - "type": "type", - "attributes": { - "first_name": "foo", - "last_name": "bar" - }, - "date_created": "2019-07-31T02:11:52Z", - "date_updated": "2019-07-31T02:11:52Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_documents.create(friendly_name="friendly_name", type="type") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_documents.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_documents.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "results": [ - { - "sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "mime_type": "mime_type", - "status": "draft", - "type": "type", - "attributes": { - "first_name": "foo", - "last_name": "bar" - }, - "date_created": "2019-07-31T02:11:52Z", - "date_updated": "2019-07-31T02:11:52Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments?PageSize=50&Page=0", - "next_page_url": null, - "key": "results" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_documents.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_documents("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "mime_type": "mime_type", - "status": "draft", - "type": "type", - "attributes": { - "first_name": "foo", - "last_name": "bar" - }, - "date_created": "2019-07-31T02:11:52Z", - "date_updated": "2019-07-31T02:11:52Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_documents("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_documents("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "mime_type": "mime_type", - "status": "draft", - "type": "type", - "attributes": { - "first_name": "foo", - "last_name": "bar" - }, - "date_created": "2019-07-31T02:11:52Z", - "date_updated": "2019-07-31T02:11:52Z", - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_documents("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document_type.py b/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document_type.py deleted file mode 100644 index 945a916a78..0000000000 --- a/tests/integration/numbers/v2/regulatory_compliance/test_supporting_document_type.py +++ /dev/null @@ -1,126 +0,0 @@ -# coding=utf-8 -r""" -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 SupportingDocumentTypeTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_document_types.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "supporting_document_types": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes?PageSize=50&Page=0", - "next_page_url": null, - "key": "supporting_document_types" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_document_types.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "supporting_document_types": [ - { - "sid": "OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Passport", - "machine_name": "passport", - "fields": [ - { - "friendly_name": "Last Name", - "machine_name": "last_name", - "constraint": "String" - } - ], - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes/OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes?PageSize=50&Page=0", - "next_page_url": null, - "key": "supporting_document_types" - } - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_document_types.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.numbers.v2.regulatory_compliance \ - .supporting_document_types("OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes/OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Passport", - "machine_name": "passport", - "fields": [ - { - "friendly_name": "Last Name", - "machine_name": "last_name", - "constraint": "String" - } - ], - "url": "https://numbers.twilio.com/v2/RegulatoryCompliance/SupportingDocumentTypes/OYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.numbers.v2.regulatory_compliance \ - .supporting_document_types("OYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/numbers/v2/test_regulatory_compliance.py b/tests/integration/numbers/v2/test_regulatory_compliance.py deleted file mode 100644 index f8a11c4f39..0000000000 --- a/tests/integration/numbers/v2/test_regulatory_compliance.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 RegulatoryComplianceTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/preview/__init__.py b/tests/integration/preview/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/bulk_exports/__init__.py b/tests/integration/preview/bulk_exports/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/bulk_exports/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/bulk_exports/export/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 342c870aaa..0000000000 --- a/tests/integration/preview/bulk_exports/export/test_day.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding=utf-8 -r""" -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_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports("resource_type") \ - .days("day").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Days/day', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "redirect_to": "https://www.twilio.com" - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .days("day").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports("resource_type") \ - .days.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Days', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "days": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "next_page_url": null, - "key": "days" - } - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .days.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "days": [ - { - "day": "2017-04-01", - "size": 100, - "resource_type": "Calls", - "create_date": "2017-04-02", - "friendly_name": "friendly_name" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://preview.twilio.com/BulkExports/Exports/Calls/Days?PageSize=50&Page=0", - "next_page_url": null, - "key": "days" - } - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .days.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/bulk_exports/export/test_export_custom_job.py b/tests/integration/preview/bulk_exports/export/test_export_custom_job.py deleted file mode 100644 index 77e169804a..0000000000 --- a/tests/integration/preview/bulk_exports/export/test_export_custom_job.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -r""" -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 ExportCustomJobTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports("resource_type") \ - .export_custom_jobs.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Jobs', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "url": "https://preview.twilio.com/BulkExports/Exports/Messages/Jobs?PageSize=50&Page=0", - "page_size": 50, - "key": "jobs", - "first_page_url": "https://preview.twilio.com/BulkExports/Exports/Messages/Jobs?PageSize=50&Page=0", - "next_page_url": null, - "page": 0 - }, - "jobs": [] - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .export_custom_jobs.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "previous_page_url": null, - "url": "https://preview.twilio.com/BulkExports/Exports/Messages/Jobs?PageSize=50&Page=0", - "page_size": 50, - "key": "jobs", - "first_page_url": "https://preview.twilio.com/BulkExports/Exports/Messages/Jobs?PageSize=50&Page=0", - "next_page_url": null, - "page": 0 - }, - "jobs": [ - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "webhook_method": "webhook_method", - "details": {}, - "end_day": "end_day", - "webhook_url": "webhook_url", - "email": "email", - "resource_type": "resource_type" - } - ] - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .export_custom_jobs.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports("resource_type") \ - .export_custom_jobs.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/BulkExports/Exports/resource_type/Jobs', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "webhook_method": "webhook_method", - "details": {}, - "end_day": "end_day", - "webhook_url": "webhook_url", - "email": "email", - "resource_type": "resource_type" - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports("resource_type") \ - .export_custom_jobs.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/bulk_exports/export/test_job.py b/tests/integration/preview/bulk_exports/export/test_job.py deleted file mode 100644 index 09f7b27b12..0000000000 --- a/tests/integration/preview/bulk_exports/export/test_job.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -r""" -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 JobTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/BulkExports/Exports/Jobs/JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "start_day": "start_day", - "job_sid": "JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/BulkExports/Exports/Jobs/JSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "end_day": "end_day", - "details": {}, - "webhook_url": "webhook_url", - "webhook_method": "webhook_method", - "email": "email", - "resource_type": "resource_type" - } - ''' - )) - - actual = self.client.preview.bulk_exports.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.bulk_exports.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/BulkExports/Exports/Jobs/JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.bulk_exports.exports \ - .jobs("JSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 d3c691e73e..0000000000 --- a/tests/integration/preview/bulk_exports/test_export.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -r""" -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").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").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 e41ff88960..0000000000 --- a/tests/integration/preview/bulk_exports/test_export_configuration.py +++ /dev/null @@ -1,73 +0,0 @@ -# coding=utf-8 -r""" -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").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").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").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").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 c9fc143806..0000000000 --- a/tests/integration/preview/deployed_devices/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 a77489cc4b..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_certificate.py +++ /dev/null @@ -1,218 +0,0 @@ -# coding=utf-8 -r""" -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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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("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("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("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("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("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .certificates("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 fd5281e3b9..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_deployment.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding=utf-8 -r""" -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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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("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("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("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("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("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("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 f38fbe07b9..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_device.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -r""" -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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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("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("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("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("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("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .devices("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 c276cffa52..0000000000 --- a/tests/integration/preview/deployed_devices/fleet/test_key.py +++ /dev/null @@ -1,215 +0,0 @@ -# coding=utf-8 -r""" -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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("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("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("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("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("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .keys("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 3bab63d6fd..0000000000 --- a/tests/integration/preview/deployed_devices/test_fleet.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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 c9fc143806..0000000000 --- a/tests/integration/preview/hosted_numbers/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/hosted_numbers/authorization_document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 ba9d32a0ac..0000000000 --- a/tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding=utf-8 -r""" -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("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?Status=completed&FriendlyName=example&PhoneNumber=%2B19193608000&UniqueName=something123&IncomingPhoneNumberSid=PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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?Status=completed&FriendlyName=example&PhoneNumber=%2B19193608000&UniqueName=something123&IncomingPhoneNumberSid=PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - }, - "items": [] - } - ''' - )) - - actual = self.client.preview.hosted_numbers.authorization_documents("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("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 6bdce2afed..0000000000 --- a/tests/integration/preview/hosted_numbers/test_authorization_document.py +++ /dev/null @@ -1,213 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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?Status=signed&Email=test%2Bhosted%40twilio.com&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?Status=signed&Email=test%2Bhosted%40twilio.com&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", contact_title="contact_title", contact_phone_number="contact_phone_number") - - values = { - 'HostedNumberOrderSids': serialize.map(['hosted_number_order_sids'], lambda e: e), - 'AddressSid': "ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'Email': "email", - 'ContactTitle': "contact_title", - 'ContactPhoneNumber': "contact_phone_number", - } - - 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", contact_title="contact_title", contact_phone_number="contact_phone_number") - - 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 634edffe25..0000000000 --- a/tests/integration/preview/hosted_numbers/test_hosted_number_order.py +++ /dev/null @@ -1,371 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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?Status=completed&FriendlyName=example&PhoneNumber=%2B19193608000&UniqueName=something123&IncomingPhoneNumberSid=PNzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz&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?Status=completed&FriendlyName=example&PhoneNumber=%2B19193608000&UniqueName=something123&IncomingPhoneNumberSid=PNzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz&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 c9fc143806..0000000000 --- a/tests/integration/preview/marketplace/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/marketplace/available_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 5512e21bbf..0000000000 --- a/tests/integration/preview/marketplace/available_add_on/test_available_add_on_extension.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding=utf-8 -r""" -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("XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("XBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("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("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("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 c9fc143806..0000000000 --- a/tests/integration/preview/marketplace/installed_add_on/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 da25ed86b7..0000000000 --- a/tests/integration/preview/marketplace/installed_add_on/test_installed_add_on_extension.py +++ /dev/null @@ -1,154 +0,0 @@ -# coding=utf-8 -r""" -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("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .extensions("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("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("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("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 31f830e661..0000000000 --- a/tests/integration/preview/marketplace/test_available_add_on.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 471c90f808..0000000000 --- a/tests/integration/preview/marketplace/test_installed_add_on.py +++ /dev/null @@ -1,231 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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/sync/__init__.py b/tests/integration/preview/sync/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/sync/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/sync/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 37710a8988..0000000000 --- a/tests/integration/preview/sync/service/document/test_document_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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 c9fc143806..0000000000 --- a/tests/integration/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c0847d4afb..0000000000 --- a/tests/integration/preview/sync/service/sync_list/test_sync_list_item.py +++ /dev/null @@ -1,245 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).update(data={}, if_match="if_match") - - values = {'Data': serialize.object({}), } - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - headers=headers, - )) - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(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 d56c30daf4..0000000000 --- a/tests/integration/preview/sync/service/sync_list/test_sync_list_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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 c9fc143806..0000000000 --- a/tests/integration/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 088be1c979..0000000000 --- a/tests/integration/preview/sync/service/sync_map/test_sync_map_item.py +++ /dev/null @@ -1,245 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").update(data={}, if_match="if_match") - - values = {'Data': serialize.object({}), } - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - headers=headers, - )) - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("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 f4c7798c64..0000000000 --- a/tests/integration/preview/sync/service/sync_map/test_sync_map_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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 21e1e6bf2f..0000000000 --- a/tests/integration/preview/sync/service/test_document.py +++ /dev/null @@ -1,243 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(data={}, if_match="if_match") - - values = {'Data': serialize.object({}), } - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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 8148fdaf39..0000000000 --- a/tests/integration/preview/sync/service/test_sync_list.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("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("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("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("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("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 5bd31de2fb..0000000000 --- a/tests/integration/preview/sync/service/test_sync_map.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("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("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("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("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("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 733c31bb36..0000000000 --- a/tests/integration/preview/sync/test_service.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -r""" -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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.sync.services("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/__init__.py b/tests/integration/preview/trusted_comms/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/trusted_comms/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/trusted_comms/business/__init__.py b/tests/integration/preview/trusted_comms/business/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/trusted_comms/business/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/trusted_comms/business/brand/__init__.py b/tests/integration/preview/trusted_comms/business/brand/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/trusted_comms/business/brand/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/trusted_comms/business/brand/branded_channel/__init__.py b/tests/integration/preview/trusted_comms/business/brand/branded_channel/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/trusted_comms/business/brand/branded_channel/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/trusted_comms/business/brand/branded_channel/test_channel.py b/tests/integration/preview/trusted_comms/business/brand/branded_channel/test_channel.py deleted file mode 100644 index e8e5d43e0d..0000000000 --- a/tests/integration/preview/trusted_comms/business/brand/branded_channel/test_channel.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -r""" -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_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .branded_channels("BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'PhoneNumberSid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/TrustedComms/Businesses/BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Brands/BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/BrandedChannels/BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Channels', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "brand_sid": "BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "branded_channel_sid": "BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "phone_number": "+15000000000", - "url": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands/BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BrandedChannels/BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - } - ''' - )) - - actual = self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .branded_channels("BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .channels.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/business/brand/test_branded_channel.py b/tests/integration/preview/trusted_comms/business/brand/test_branded_channel.py deleted file mode 100644 index 1cc20cd1c2..0000000000 --- a/tests/integration/preview/trusted_comms/business/brand/test_branded_channel.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -r""" -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 BrandedChannelTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .branded_channels("BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/Businesses/BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Brands/BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/BrandedChannels/BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "brand_sid": "BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "channels": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands/BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BrandedChannels/BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels" - }, - "url": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands/BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BrandedChannels/BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .branded_channels("BWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/business/insights/__init__.py b/tests/integration/preview/trusted_comms/business/insights/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/trusted_comms/business/insights/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/trusted_comms/business/insights/test_impressions_rate.py b/tests/integration/preview/trusted_comms/business/insights/test_impressions_rate.py deleted file mode 100644 index cb17a1ca18..0000000000 --- a/tests/integration/preview/trusted_comms/business/insights/test_impressions_rate.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -r""" -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 ImpressionsRateTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .insights \ - .impressions_rate().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/Businesses/BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Insights/ImpressionsRate', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "start": "2015-07-30T20:00:00Z", - "end": "2015-07-30T21:00:00Z", - "interval": "minute", - "reports": { - "impressions_rate": { - "timestamp": "2015-07-30T20:00:00", - "calls": 1200, - "impressions": 800 - } - }, - "url": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Insights/ImpressionsRate" - } - ''' - )) - - actual = self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .insights \ - .impressions_rate().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/business/test_brand.py b/tests/integration/preview/trusted_comms/business/test_brand.py deleted file mode 100644 index 4c09edbdf4..0000000000 --- a/tests/integration/preview/trusted_comms/business/test_brand.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -r""" -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 BrandTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/Businesses/BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Brands/BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "branded_channels": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands/BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/BrandedChannels" - }, - "url": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands/BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .brands("BZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/business/test_insights.py b/tests/integration/preview/trusted_comms/business/test_insights.py deleted file mode 100644 index 555c1dd550..0000000000 --- a/tests/integration/preview/trusted_comms/business/test_insights.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 InsightsTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/preview/trusted_comms/test_branded_call.py b/tests/integration/preview/trusted_comms/test_branded_call.py deleted file mode 100644 index 24ada8d72e..0000000000 --- a/tests/integration/preview/trusted_comms/test_branded_call.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -r""" -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 BrandedCallTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.branded_calls.create(from_="from", to="to", reason="reason") - - values = {'From': "from", 'To': "to", 'Reason': "reason", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/TrustedComms/Business/BrandedCalls', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bg_color": "#fff", - "brand_sid": "BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "branded_channel_sid": "BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "caller": "Owl Bank", - "created_at": "2019-05-01T20:00:00Z", - "font_color": "#000", - "from": "+15000000000", - "logo": "https://www.twilio.com/marketing/bundles/company/img/logos/red/twilio-logo-red.png", - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason": "Hello Jhon, your appointment has been confirmed.", - "sid": "CQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "unknown", - "to": "+573000000000", - "use_case": "conversational", - "url": "https://preview.twilio.com/TrustedComms/Business/BrandedCalls" - } - ''' - )) - - actual = self.client.preview.trusted_comms.branded_calls.create(from_="from", to="to", reason="reason") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/test_brands_information.py b/tests/integration/preview/trusted_comms/test_brands_information.py deleted file mode 100644 index aae583f0d8..0000000000 --- a/tests/integration/preview/trusted_comms/test_brands_information.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -r""" -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 BrandsInformationTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.brands_information().fetch(if_none_match="if_none_match") - - headers = {'If-None-Match': "if_none_match", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/BrandsInformation', - headers=headers, - )) - - def test_fetch_results_with_etag_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "update_time": "2020-05-19T19:47:51Z", - "file_link": "https://www.twilio.com", - "file_link_ttl_in_seconds": "900", - "url": "https://preview.twilio.com/TrustedComms/BrandsInformation" - } - ''' - )) - - actual = self.client.preview.trusted_comms.brands_information().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/test_business.py b/tests/integration/preview/trusted_comms/test_business.py deleted file mode 100644 index 019000c49b..0000000000 --- a/tests/integration/preview/trusted_comms/test_business.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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 BusinessTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/Businesses/BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "brands": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Brands", - "insights": "https://preview.twilio.com/TrustedComms/Businesses/BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Insights" - } - } - ''' - )) - - actual = self.client.preview.trusted_comms.businesses("BXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/test_cps.py b/tests/integration/preview/trusted_comms/test_cps.py deleted file mode 100644 index 0767419733..0000000000 --- a/tests/integration/preview/trusted_comms/test_cps.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -r""" -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 CpsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.cps().fetch(x_xcnam_sensitive_phone_number="x_xcnam_sensitive_phone_number") - - headers = {'X-Xcnam-Sensitive-Phone-Number': "x_xcnam_sensitive_phone_number", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/CPS', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "cps_url": "https://preview.twilio.com/TrustedComms/CurrentCall", - "phone_number": "+1500123", - "url": "https://preview.twilio.com/TrustedComms/CPS" - } - ''' - )) - - actual = self.client.preview.trusted_comms.cps().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/test_current_call.py b/tests/integration/preview/trusted_comms/test_current_call.py deleted file mode 100644 index 9459f31a99..0000000000 --- a/tests/integration/preview/trusted_comms/test_current_call.py +++ /dev/null @@ -1,58 +0,0 @@ -# coding=utf-8 -r""" -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 CurrentCallTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.current_calls().fetch(x_xcnam_sensitive_phone_number_from="x_xcnam_sensitive_phone_number_from", x_xcnam_sensitive_phone_number_to="x_xcnam_sensitive_phone_number_to") - - headers = { - 'X-Xcnam-Sensitive-Phone-Number-From': "x_xcnam_sensitive_phone_number_from", - 'X-Xcnam-Sensitive-Phone-Number-To': "x_xcnam_sensitive_phone_number_to", - } - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/TrustedComms/CurrentCall', - headers=headers, - )) - - def test_read_found_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "bg_color": "#fff", - "caller": "Owl Bank", - "created_at": "2019-05-01T20:00:00Z", - "font_color": "#f22f46", - "from": "+1500123", - "logo": "https://www.twilio.com/marketing/bundles/company/img/logos/red/twilio-logo-red.png", - "manager": "Twilio", - "reason": "Hello Jhon, your bank appointment has been confirmed.", - "shield_img": "https://www.twilio.com/marketing/bundles/company/img/badges/red/twilio-badge-red.png", - "sid": "CQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "ringing", - "to": "+1500456", - "url": "https://preview.twilio.com/TrustedComms/CurrentCall", - "use_case": "conversational" - } - ''' - )) - - actual = self.client.preview.trusted_comms.current_calls().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/trusted_comms/test_phone_call.py b/tests/integration/preview/trusted_comms/test_phone_call.py deleted file mode 100644 index 0f2cbe29a6..0000000000 --- a/tests/integration/preview/trusted_comms/test_phone_call.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -r""" -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 PhoneCallTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.trusted_comms.phone_calls.create(from_="from", to="to") - - values = {'From': "from", 'To': "to", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/TrustedComms/Business/PhoneCalls', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bg_color": "#fff", - "brand_sid": "BZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "branded_channel_sid": "BWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "business_sid": "BXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "call_sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "caller": "Owl Bank", - "created_at": "2019-05-01T20:00:00Z", - "font_color": "#000", - "from": "+15000000000", - "logo": "https://www.twilio.com/marketing/bundles/company/img/logos/red/twilio-logo-red.png", - "phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "reason": "Hello Jhon, your appointment has been confirmed.", - "sid": "CQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "unknown", - "to": "+573000000000", - "url": "https://preview.twilio.com/TrustedComms/Business/PhoneCalls", - "use_case": "conversational" - } - ''' - )) - - actual = self.client.preview.trusted_comms.phone_calls.create(from_="from", to="to") - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/__init__.py b/tests/integration/preview/understand/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/understand/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/understand/assistant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/understand/assistant/field_type/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 0906eaa388..0000000000 --- a/tests/integration/preview/understand/assistant/field_type/test_field_value.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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?Language=language&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?Language=language&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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?Language=language&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?Language=language&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_values("UCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/task/__init__.py b/tests/integration/preview/understand/assistant/task/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/preview/understand/assistant/task/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/preview/understand/assistant/task/test_field.py b/tests/integration/preview/understand/assistant/task/test_field.py deleted file mode 100644 index 1cf5396fa7..0000000000 --- a/tests/integration/preview/understand/assistant/task/test_field.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields?PageSize=50&Page=0", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields/UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "sid": "UEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "field_type": "field_type" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields/UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .fields("UEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/task/test_sample.py b/tests/integration/preview/understand/assistant/task/test_sample.py deleted file mode 100644 index 2d50291ad2..0000000000 --- a/tests/integration/preview/understand/assistant/task/test_sample.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "previous_page_url": null, - "key": "samples", - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples?Language=language&PageSize=50&Page=0", - "page": 0, - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples/UFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Samples/UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .samples("UFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/task/test_task_actions.py b/tests/integration/preview/understand/assistant/task/test_task_actions.py deleted file mode 100644 index 1aacc42060..0000000000 --- a/tests/integration/preview/understand/assistant/task/test_task_actions.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding=utf-8 -r""" -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 TaskActionsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Actions', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDdddddddddddddddddddddddddddddddd", - "data": {}, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDdddddddddddddddddddddddddddddddd/Actions" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Actions', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDdddddddddddddddddddddddddddddddd", - "data": {}, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDdddddddddddddddddddddddddddddddd/Actions" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_actions().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/assistant/task/test_task_statistics.py b/tests/integration/preview/understand/assistant/task/test_task_statistics.py deleted file mode 100644 index e372ebd358..0000000000 --- a/tests/integration/preview/understand/assistant/task/test_task_statistics.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -r""" -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 TaskStatisticsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "task_sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "samples_count": 0, - "fields_count": 0 - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .statistics().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/assistant/test_assistant_fallback_actions.py b/tests/integration/preview/understand/assistant/test_assistant_fallback_actions.py deleted file mode 100644 index 91c9ebb24c..0000000000 --- a/tests/integration/preview/understand/assistant/test_assistant_fallback_actions.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -r""" -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 AssistantFallbackActionsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_fallback_actions().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FallbackActions', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "data": {} - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_fallback_actions().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_fallback_actions().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/FallbackActions', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "data": {} - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_fallback_actions().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/assistant/test_assistant_initiation_actions.py b/tests/integration/preview/understand/assistant/test_assistant_initiation_actions.py deleted file mode 100644 index b59a428a08..0000000000 --- a/tests/integration/preview/understand/assistant/test_assistant_initiation_actions.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -r""" -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 AssistantInitiationActionsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_initiation_actions().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/InitiationActions', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": {}, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_initiation_actions().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_initiation_actions().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/InitiationActions', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions", - "data": {} - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assistant_initiation_actions().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/assistant/test_dialogue.py b/tests/integration/preview/understand/assistant/test_dialogue.py deleted file mode 100644 index 9df32e6db0..0000000000 --- a/tests/integration/preview/understand/assistant/test_dialogue.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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 DialogueTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dialogues("UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Dialogues/UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UKkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues/UKkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", - "data": {} - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .dialogues("UKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(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 6f1a580b6a..0000000000 --- a/tests/integration/preview/understand/assistant/test_field_type.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("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("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("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("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("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .field_types("UBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").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 e2d4f10b30..0000000000 --- a/tests/integration/preview/understand/assistant/test_model_build.py +++ /dev/null @@ -1,219 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("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("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("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("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("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("UGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .model_builds("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 ae92eed930..0000000000 --- a/tests/integration/preview/understand/assistant/test_query.py +++ /dev/null @@ -1,286 +0,0 @@ -# coding=utf-8 -r""" -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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("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": { - "task": { - "name": "name", - "task_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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("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?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("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": { - "task": { - "name": "name", - "task_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?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page": 0, - "key": "queries", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries?Status=status&ModelBuild=UGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Language=language&PageSize=50&Page=0", - "page_size": 50 - } - } - ''' - )) - - actual = self.client.preview.understand.assistants("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("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": { - "task": { - "name": "name", - "task_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("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("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": { - "task": { - "name": "name", - "task_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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .queries("UHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/preview/understand/assistant/test_style_sheet.py b/tests/integration/preview/understand/assistant/test_style_sheet.py deleted file mode 100644 index 608ef12941..0000000000 --- a/tests/integration/preview/understand/assistant/test_style_sheet.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -r""" -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 StyleSheetTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/StyleSheet', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data": {}, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/StyleSheet', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet", - "data": {} - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .style_sheet().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/preview/understand/assistant/test_task.py b/tests/integration/preview/understand/assistant/test_task.py deleted file mode 100644 index d75e5b7015..0000000000 --- a/tests/integration/preview/understand/assistant/test_task.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "tasks", - "page_size": 50, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "previous_page_url": null - }, - "tasks": [] - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "key": "tasks", - "page_size": 50, - "next_page_url": null, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks?PageSize=50&Page=0", - "previous_page_url": null - }, - "tasks": [ - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ] - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks', - 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/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks.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("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "unique_name", - "links": { - "fields": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Fields", - "samples": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Samples", - "task_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Actions", - "statistics": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks/UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "UDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_updated": "2015-07-30T20:00:00Z", - "assistant_sid": "UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "actions_url": "https://example.com/actions_url" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://preview.twilio.com/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").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 10f63a37cb..0000000000 --- a/tests/integration/preview/understand/test_assistant.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "assistant_fallback_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "assistant_initiation_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions", - "dialogues": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "style_sheet": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.preview.understand.assistants("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", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "assistant_fallback_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "assistant_initiation_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions", - "dialogues": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "style_sheet": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "assistant_fallback_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "assistant_initiation_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions", - "dialogues": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "style_sheet": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("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", - "unique_name": "so-so-unique", - "links": { - "field_types": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FieldTypes", - "tasks": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tasks", - "model_builds": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ModelBuilds", - "queries": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Queries", - "assistant_fallback_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/FallbackActions", - "assistant_initiation_actions": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/InitiationActions", - "dialogues": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Dialogues", - "style_sheet": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/StyleSheet" - }, - "url": "https://preview.twilio.com/understand/Assistants/UAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "callback_url": "https://example.com/callback_url", - "callback_events": "model_build_completed model_build_failed" - } - ''' - )) - - actual = self.client.preview.understand.assistants("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.preview.understand.assistants("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("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 c9fc143806..0000000000 --- a/tests/integration/preview/wireless/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/preview/wireless/sim/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 6b95e04166..0000000000 --- a/tests/integration/preview/wireless/sim/test_usage.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 59e58a64a8..0000000000 --- a/tests/integration/preview/wireless/test_command.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -r""" -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("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("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?Device=device&Status=status&Direction=direction&Sim=sim&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?Device=device&Status=status&Direction=direction&Sim=sim&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?Device=device&Status=status&Direction=direction&Sim=sim&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?Device=device&Status=status&Direction=direction&Sim=sim&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 c286db7696..0000000000 --- a/tests/integration/preview/wireless/test_rate_plan.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("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("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("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("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 15d59d9e62..0000000000 --- a/tests/integration/preview/wireless/test_sim.py +++ /dev/null @@ -1,198 +0,0 @@ -# coding=utf-8 -r""" -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("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("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?Status=status&Iccid=iccid&RatePlan=rate_plan&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?Status=status&Iccid=iccid&RatePlan=rate_plan&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?Status=status&Iccid=iccid&RatePlan=rate_plan&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?Status=status&Iccid=iccid&RatePlan=rate_plan&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("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("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/__init__.py b/tests/integration/pricing/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/pricing/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/pricing/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/pricing/v1/messaging/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 6e19734b6a..0000000000 --- a/tests/integration/pricing/v1/messaging/test_country.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -r""" -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?PageSize=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Messaging/Countries?PageSize=50&Page=0" - } - } - ''' - )) - - 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": "https://pricing.twilio.com/v1/Messaging/Countries/US" - } - ], - "meta": { - "first_page_url": "https://pricing.twilio.com/v1/Messaging/Countries?PageSize=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Messaging/Countries?PageSize=50&Page=0" - } - } - ''' - )) - - 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("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": "https://pricing.twilio.com/v1/Messaging/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v1.messaging \ - .countries("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 c9fc143806..0000000000 --- a/tests/integration/pricing/v1/phone_number/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 814fa3879f..0000000000 --- a/tests/integration/pricing/v1/phone_number/test_country.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding=utf-8 -r""" -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": { - "page": 0, - "page_size": 50, - "first_page_url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=50&Page=0", - "next_page_url": null, - "key": "countries" - } - } - ''' - )) - - 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=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries?PageSize=50&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("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": "United States", - "iso_country": "US", - "phone_number_prices": [ - { - "number_type": "local", - "base_price": "1.00", - "current_price": "1.00" - }, - { - "number_type": "toll free", - "base_price": "2.00", - "current_price": "2.00" - } - ], - "price_unit": "USD", - "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v1.phone_numbers \ - .countries("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 057e373c23..0000000000 --- a/tests/integration/pricing/v1/test_messaging.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 d8ec5cef59..0000000000 --- a/tests/integration/pricing/v1/test_phone_number.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 948a1534e4..0000000000 --- a/tests/integration/pricing/v1/test_voice.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/pricing/v1/voice/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 dc0aa2f930..0000000000 --- a/tests/integration/pricing/v1/voice/test_country.py +++ /dev/null @@ -1,133 +0,0 @@ -# coding=utf-8 -r""" -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=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=50&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=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v1/Voice/Countries?PageSize=50&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("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": "United States", - "inbound_call_prices": [ - { - "current_price": "0.0085", - "number_type": "local", - "base_price": "0.0085" - }, - { - "current_price": "0.022", - "number_type": "toll free", - "base_price": "0.022" - } - ], - "iso_country": "US", - "outbound_prefix_prices": [ - { - "prefixes": [ - "1907" - ], - "current_price": "0.090", - "friendly_name": "Programmable Outbound Minute - United States - Alaska", - "base_price": "0.090" - } - ], - "price_unit": "USD", - "url": "https://pricing.twilio.com/v1/Voice/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .countries("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 a9c696b80d..0000000000 --- a/tests/integration/pricing/v1/voice/test_number.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -r""" -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("+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": "Iran", - "inbound_call_price": { - "base_price": null, - "current_price": null, - "number_type": null - }, - "iso_country": "IR", - "number": "+987654321", - "outbound_call_price": { - "base_price": "0.255", - "current_price": "0.255" - }, - "price_unit": "USD", - "url": "https://pricing.twilio.com/v1/Voice/Numbers/+987654321" - } - ''' - )) - - actual = self.client.pricing.v1.voice \ - .numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/v2/__init__.py b/tests/integration/pricing/v2/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/pricing/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v2/test_voice.py b/tests/integration/pricing/v2/test_voice.py deleted file mode 100644 index 948a1534e4..0000000000 --- a/tests/integration/pricing/v2/test_voice.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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/v2/voice/__init__.py b/tests/integration/pricing/v2/voice/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/pricing/v2/voice/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/pricing/v2/voice/test_country.py b/tests/integration/pricing/v2/voice/test_country.py deleted file mode 100644 index c22a448c16..0000000000 --- a/tests/integration/pricing/v2/voice/test_country.py +++ /dev/null @@ -1,174 +0,0 @@ -# coding=utf-8 -r""" -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.v2.voice \ - .countries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v2/Voice/Countries', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "countries": [ - { - "country": "Andorra", - "iso_country": "AD", - "url": "https://pricing.twilio.com/v2/Voice/Countries/AD" - } - ], - "meta": { - "first_page_url": "https://pricing.twilio.com/v2/Voice/Countries?PageSize=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v2/Voice/Countries?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v2.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/v2/Voice/Countries?PageSize=50&Page=0", - "key": "countries", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://pricing.twilio.com/v2/Voice/Countries?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.pricing.v2.voice \ - .countries.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.pricing.v2.voice \ - .countries("US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v2/Voice/Countries/US', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "United States", - "inbound_call_prices": [ - { - "base_price": "0.0085", - "current_price": "0.0085", - "number_type": "local" - }, - { - "base_price": "0.022", - "current_price": "0.022", - "number_type": "toll free" - } - ], - "iso_country": "US", - "outbound_prefix_prices": [ - { - "base_price": "0.090", - "current_price": "0.090", - "destination_prefixes": [ - "1907" - ], - "friendly_name": "Programmable Outbound Minute - United States - Alaska", - "origination_prefixes": [ - "ALL" - ] - }, - { - "base_price": "0.013", - "current_price": "0.013", - "destination_prefixes": [ - "1808" - ], - "friendly_name": "Programmable Outbound Minute - United States - Hawaii", - "origination_prefixes": [ - "ALL" - ] - }, - { - "base_price": "0.013", - "current_price": "0.013", - "destination_prefixes": [ - "1800", - "1844", - "1855", - "1866", - "1877", - "1888" - ], - "friendly_name": "Programmable Outbound Minute - United States & Canada - Toll Free", - "origination_prefixes": [ - "ALL" - ] - }, - { - "base_price": "0.013", - "current_price": "0.013", - "destination_prefixes": [ - "1" - ], - "friendly_name": "Programmable Outbound Minute - United States & Canada", - "origination_prefixes": [ - "ALL" - ] - } - ], - "price_unit": "USD", - "url": "https://pricing.twilio.com/v2/Voice/Countries/US" - } - ''' - )) - - actual = self.client.pricing.v2.voice \ - .countries("US").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/pricing/v2/voice/test_number.py b/tests/integration/pricing/v2/voice/test_number.py deleted file mode 100644 index 5b3f6fb8fd..0000000000 --- a/tests/integration/pricing/v2/voice/test_number.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding=utf-8 -r""" -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.v2.voice \ - .numbers("+15017122661").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://pricing.twilio.com/v2/Voice/Numbers/+15017122661', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "country": "United States", - "destination_number": "+18001234567", - "inbound_call_price": { - "base_price": null, - "current_price": null, - "number_type": null - }, - "iso_country": "US", - "origination_number": "+987654321", - "outbound_call_prices": [ - { - "base_price": "0.013", - "current_price": "0.013", - "origination_prefixes": [ - "ALL" - ] - } - ], - "price_unit": "USD", - "url": "https://pricing.twilio.com/v2/Voice/Numbers/+18001234567" - } - ''' - )) - - actual = self.client.pricing.v2.voice \ - .numbers("+15017122661").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/proxy/__init__.py b/tests/integration/proxy/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/proxy/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/proxy/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/proxy/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/proxy/v1/service/session/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/proxy/v1/service/session/participant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 b25f19d7cd..0000000000 --- a/tests/integration/proxy/v1/service/session/participant/test_message_interaction.py +++ /dev/null @@ -1,155 +0,0 @@ -# coding=utf-8 -r""" -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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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\\":\\"some message\\"}", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions("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": "{\\"body\\":\\"some message\\"}", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .message_interactions("KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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 9d9963464e..0000000000 --- a/tests/integration/proxy/v1/service/session/test_interaction.py +++ /dev/null @@ -1,125 +0,0 @@ -# coding=utf-8 -r""" -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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions("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": "{\\"body\\":\\"some message\\"}", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions("KIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .interactions("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 b42007f543..0000000000 --- a/tests/integration/proxy/v1/service/session/test_participant.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -r""" -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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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": "+14155551212", - "proxy_identifier": "+14155559999", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_channel_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identifier": "messenger:14155551212", - "proxy_identifier": "messenger:14155559999", - "proxy_identifier_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "a facebook user", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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": "+14155551212", - "proxy_identifier": "+14155559999", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants.create(identifier="identifier") - - self.assertIsNotNone(actual) - - def test_create_channel_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "KPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "session_sid": "KCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identifier": "messenger:123456", - "proxy_identifier": "messenger:987654532", - "proxy_identifier_sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "a facebook user", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("KPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 1827b6b9ff..0000000000 --- a/tests/integration/proxy/v1/service/test_phone_number.py +++ /dev/null @@ -1,215 +0,0 @@ -# coding=utf-8 -r""" -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("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": "+1987654321", - "friendly_name": "Friendly Name", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "is_reserved": false, - "in_use": 0 - } - ''' - )) - - actual = self.client.proxy.v1.services("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("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": "+1987654321", - "friendly_name": "Friendly Name", - "iso_country": "US", - "capabilities": { - "sms_outbound": true, - "voice_inbound": false - }, - "url": "https://proxy.twilio.com/v1/Services/KSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "is_reserved": false, - "in_use": 0 - } - ] - } - ''' - )) - - actual = self.client.proxy.v1.services("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("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", - "is_reserved": false, - "in_use": 0 - } - ''' - )) - - actual = self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_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", - "is_reserved": true, - "in_use": 0 - } - ''' - )) - - actual = self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - 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 9a3c7e8d34..0000000000 --- a/tests/integration/proxy/v1/service/test_session.py +++ /dev/null @@ -1,209 +0,0 @@ -# coding=utf-8 -r""" -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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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": "open", - "unique_name": "Order #1234", - "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": "voice-and-message", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("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("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("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": "open", - "unique_name": "Order #1234", - "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": "voice-and-message", - "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("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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": "Order #1234", - "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": "voice-and-message", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sessions("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 e02d56e38b..0000000000 --- a/tests/integration/proxy/v1/service/test_short_code.py +++ /dev/null @@ -1,210 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "is_reserved": false - } - ''' - )) - - actual = self.client.proxy.v1.services("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("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", - "is_reserved": false - } - ] - } - ''' - )) - - actual = self.client.proxy.v1.services("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("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", - "is_reserved": false - } - ''' - )) - - actual = self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://proxy.twilio.com/v1/Services/KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ShortCodes/SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_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", - "is_reserved": true - } - ''' - )) - - actual = self.client.proxy.v1.services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .short_codes("SCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - 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 4c49c31438..0000000000 --- a/tests/integration/proxy/v1/test_service.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "chat_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My Service", - "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("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", - "chat_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My Service", - "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("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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.proxy.v1.services("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", - "chat_instance_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My Service", - "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("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/__init__.py b/tests/integration/serverless/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/__init__.py b/tests/integration/serverless/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/__init__.py b/tests/integration/serverless/v1/service/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/asset/__init__.py b/tests/integration/serverless/v1/service/asset/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/service/asset/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/asset/test_asset_version.py b/tests/integration/serverless/v1/service/asset/test_asset_version.py deleted file mode 100644 index 9a757886e0..0000000000 --- a/tests/integration/serverless/v1/service/asset/test_asset_version.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding=utf-8 -r""" -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 AssetVersionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .asset_versions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Versions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "asset_versions": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions?PageSize=50&Page=0", - "key": "asset_versions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .asset_versions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .asset_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Versions/ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZN00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "asset_sid": "ZH00000000000000000000000000000000", - "path": "/test-path", - "visibility": "public", - "date_created": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions/ZN00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .asset_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/environment/__init__.py b/tests/integration/serverless/v1/service/environment/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/service/environment/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/environment/test_deployment.py b/tests/integration/serverless/v1/service/environment/test_deployment.py deleted file mode 100644 index abb3b91a01..0000000000 --- a/tests/integration/serverless/v1/service/environment/test_deployment.py +++ /dev/null @@ -1,125 +0,0 @@ -# coding=utf-8 -r""" -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_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "deployments": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments?PageSize=50&Page=0", - "key": "deployments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("ZDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/ZDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZD00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "build_sid": "ZB00000000000000000000000000000000", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments/ZD00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments("ZDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZD00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "build_sid": "ZB00000000000000000000000000000000", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments/ZD00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .deployments.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/environment/test_log.py b/tests/integration/serverless/v1/service/environment/test_log.py deleted file mode 100644 index 0e68c298d8..0000000000 --- a/tests/integration/serverless/v1/service/environment/test_log.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -r""" -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 LogTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .logs.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Logs', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "logs": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs?StartDate=2018-11-10T20%3A00%3A00Z&EndDate=2018-12-10T20%3A00%3A00Z&FunctionSid=ZH00000000000000000000000000000000&PageSize=50&Page=0", - "key": "logs", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs?StartDate=2018-11-10T20%3A00%3A00Z&EndDate=2018-12-10T20%3A00%3A00Z&FunctionSid=ZH00000000000000000000000000000000&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .logs.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .logs("NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Logs/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "NO00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "build_sid": "ZB00000000000000000000000000000000", - "deployment_sid": "ZD00000000000000000000000000000000", - "function_sid": "ZH00000000000000000000000000000000", - "request_sid": "RQ00000000000000000000000000000000", - "level": "warn", - "message": "This is a warning", - "date_created": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs/NO00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .logs("NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/environment/test_variable.py b/tests/integration/serverless/v1/service/environment/test_variable.py deleted file mode 100644 index d57862d5a3..0000000000 --- a/tests/integration/serverless/v1/service/environment/test_variable.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding=utf-8 -r""" -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 VariableTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "variables": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables?PageSize=50&Page=0", - "key": "variables", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables/ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZV00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "key": "test-key", - "value": "test-value", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables/ZV00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables.create(key="key", value="value") - - values = {'Key': "key", 'Value': "value", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZV00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "key": "new-key", - "value": "new-value", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables/ZV00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables.create(key="key", value="value") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables/ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZV00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "environment_sid": "ZE00000000000000000000000000000000", - "key": "update-key", - "value": "update-value", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-11T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables/ZV00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables/ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .variables("ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/serverless/v1/service/function/__init__.py b/tests/integration/serverless/v1/service/function/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/service/function/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/function/function_version/__init__.py b/tests/integration/serverless/v1/service/function/function_version/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/serverless/v1/service/function/function_version/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/serverless/v1/service/function/function_version/test_function_version_content.py b/tests/integration/serverless/v1/service/function/function_version/test_function_version_content.py deleted file mode 100644 index 1189d065ea..0000000000 --- a/tests/integration/serverless/v1/service/function/function_version/test_function_version_content.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -r""" -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 FunctionVersionContentTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_version_content().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Versions/ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Content', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZN00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "function_sid": "ZH00000000000000000000000000000000", - "content": "exports.handler = function (context, event, callback) {\\n const request = require(\\"request\\");\\n return request(\\"http://www.google.com\\", function (error, response, body) {\\n callback(null, response.statusCode);\\n });\\n};", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions/ZN00000000000000000000000000000000/Content" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_version_content().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/function/test_function_version.py b/tests/integration/serverless/v1/service/function/test_function_version.py deleted file mode 100644 index 8fe54f1136..0000000000 --- a/tests/integration/serverless/v1/service/function/test_function_version.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -r""" -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 FunctionVersionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Versions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "function_versions": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions?PageSize=50&Page=0", - "key": "function_versions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Versions/ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZN00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "function_sid": "ZH00000000000000000000000000000000", - "path": "/test-path", - "visibility": "public", - "date_created": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions/ZN00000000000000000000000000000000", - "links": { - "function_version_content": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions/ZN00000000000000000000000000000000/Content" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .function_versions("ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/test_asset.py b/tests/integration/serverless/v1/service/test_asset.py deleted file mode 100644 index f102be67f5..0000000000 --- a/tests/integration/serverless/v1/service/test_asset.py +++ /dev/null @@ -1,188 +0,0 @@ -# coding=utf-8 -r""" -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 AssetTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "assets": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets?PageSize=50&Page=0", - "key": "assets", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "test-asset", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000", - "links": { - "asset_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "asset-friendly", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000", - "links": { - "asset_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Assets/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "asset-friendly-update", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000", - "links": { - "asset_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .assets("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/test_build.py b/tests/integration/serverless/v1/service/test_build.py deleted file mode 100644 index e551b41144..0000000000 --- a/tests/integration/serverless/v1/service/test_build.py +++ /dev/null @@ -1,196 +0,0 @@ -# coding=utf-8 -r""" -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 BuildTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "builds": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds?PageSize=50&Page=0", - "key": "builds", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds("ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds/ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZB00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "asset_versions": [ - { - "sid": "ZN00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "asset_sid": "ZH00000000000000000000000000000000", - "date_created": "2018-11-10T20:00:00Z", - "path": "/asset-path", - "visibility": "PUBLIC" - } - ], - "function_versions": [ - { - "sid": "ZN00000000000000000000000000000001", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "function_sid": "ZH00000000000000000000000000000001", - "date_created": "2018-11-10T20:00:00Z", - "path": "/function-path", - "visibility": "PUBLIC" - } - ], - "dependencies": [ - { - "name": "twilio", - "version": "3.6.3" - } - ], - "status": "deploying", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds("ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds("ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds/ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds("ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZB00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "asset_versions": [ - { - "sid": "ZN00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "asset_sid": "ZH00000000000000000000000000000000", - "date_created": "2018-11-10T20:00:00Z", - "path": "/asset-path", - "visibility": "PUBLIC" - } - ], - "function_versions": [ - { - "sid": "ZN00000000000000000000000000000001", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "function_sid": "ZH00000000000000000000000000000001", - "date_created": "2018-11-10T20:00:00Z", - "path": "/function-path", - "visibility": "PUBLIC" - } - ], - "dependencies": [ - { - "name": "twilio", - "version": "3.6.3" - } - ], - "status": "building", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000" - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .builds.create() - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/service/test_environment.py b/tests/integration/serverless/v1/service/test_environment.py deleted file mode 100644 index f766340515..0000000000 --- a/tests/integration/serverless/v1/service/test_environment.py +++ /dev/null @@ -1,159 +0,0 @@ -# coding=utf-8 -r""" -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 EnvironmentTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "environments": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments?PageSize=50&Page=0", - "key": "environments", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZE00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "build_sid": "ZB00000000000000000000000000000000", - "unique_name": "testing-environment", - "domain_suffix": "testing", - "domain_name": "foobar-1234-testing.twil.io", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000", - "links": { - "variables": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables", - "deployments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments", - "logs": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZE00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "build_sid": null, - "unique_name": "staging", - "domain_suffix": "stage", - "domain_name": "foobar-1234-stage.twil.io", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000", - "links": { - "variables": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables", - "deployments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments", - "logs": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .environments("ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/serverless/v1/service/test_function.py b/tests/integration/serverless/v1/service/test_function.py deleted file mode 100644 index 0553162fbc..0000000000 --- a/tests/integration/serverless/v1/service/test_function.py +++ /dev/null @@ -1,188 +0,0 @@ -# coding=utf-8 -r""" -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 FunctionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "functions": [], - "meta": { - "first_page_url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0", - "key": "functions", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "test-function", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000", - "links": { - "function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "function-friendly", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000", - "links": { - "function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Functions/ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZH00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "ZS00000000000000000000000000000000", - "friendly_name": "function-friendly-update", - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000", - "links": { - "function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .functions("ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/serverless/v1/test_service.py b/tests/integration/serverless/v1/test_service.py deleted file mode 100644 index c001591212..0000000000 --- a/tests/integration/serverless/v1/test_service.py +++ /dev/null @@ -1,190 +0,0 @@ -# coding=utf-8 -r""" -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_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "services": [], - "meta": { - "first_page_url": "https://serverless.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://serverless.twilio.com/v1/Services?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.serverless.v1.services.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZS00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "test-service", - "unique_name": "test-service-1", - "include_credentials": true, - "ui_editable": false, - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000", - "links": { - "environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments", - "functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions", - "assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets", - "builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services.create(unique_name="unique_name", friendly_name="friendly_name") - - values = {'UniqueName': "unique_name", 'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "ZS00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "service-friendly", - "unique_name": "service-unique", - "include_credentials": true, - "ui_editable": false, - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000", - "links": { - "environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments", - "functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions", - "assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets", - "builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds" - } - } - ''' - )) - - actual = self.client.serverless.v1.services.create(unique_name="unique_name", friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "ZS00000000000000000000000000000000", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "service-friendly-update", - "unique_name": "service-unique-update", - "include_credentials": true, - "ui_editable": true, - "date_created": "2018-11-10T20:00:00Z", - "date_updated": "2018-11-10T20:00:00Z", - "url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000", - "links": { - "environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments", - "functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions", - "assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets", - "builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds" - } - } - ''' - )) - - actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/__init__.py b/tests/integration/studio/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/studio/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/studio/v1/flow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/studio/v1/flow/engagement/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/studio/v1/flow/engagement/step/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 4a6163ba10..0000000000 --- a/tests/integration/studio/v1/flow/engagement/step/test_step_context.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("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 e54c49e43c..0000000000 --- a/tests/integration/studio/v1/flow/engagement/test_engagement_context.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -r""" -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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("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 5d5a5447e4..0000000000 --- a/tests/integration/studio/v1/flow/engagement/test_step.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding=utf-8 -r""" -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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/execution/__init__.py b/tests/integration/studio/v1/flow/execution/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v1/flow/execution/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/execution/execution_step/__init__.py b/tests/integration/studio/v1/flow/execution/execution_step/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v1/flow/execution/execution_step/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v1/flow/execution/execution_step/test_execution_step_context.py b/tests/integration/studio/v1/flow/execution/execution_step/test_execution_step_context.py deleted file mode 100644 index 1cc8fb0a03..0000000000 --- a/tests/integration/studio/v1/flow/execution/execution_step/test_execution_step_context.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionStepContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "step_sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/execution/test_execution_context.py b/tests/integration/studio/v1/flow/execution/test_execution_context.py deleted file mode 100644 index 89bdd8d0cc..0000000000 --- a/tests/integration/studio/v1/flow/execution/test_execution_context.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .execution_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .execution_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v1/flow/execution/test_execution_step.py b/tests/integration/studio/v1/flow/execution/test_execution_step.py deleted file mode 100644 index cc820847d9..0000000000 --- a/tests/integration/studio/v1/flow/execution/test_execution_step.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionStepTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/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/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page_size": 50, - "key": "steps" - }, - "steps": [] - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_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/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "step_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("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 96414d7a94..0000000000 --- a/tests/integration/studio/v1/flow/test_engagement.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding=utf-8 -r""" -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("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("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Engagements/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .engagements("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/studio/v1/flow/test_execution.py b/tests/integration/studio/v1/flow/test_execution.py deleted file mode 100644 index cd7c156742..0000000000 --- a/tests/integration/studio/v1/flow/test_execution.py +++ /dev/null @@ -1,200 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions', - )) - - 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/Executions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions?PageSize=50&Page=0", - "page_size": 50, - "key": "executions" - }, - "executions": [] - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/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/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "steps": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.create(to="+15558675310", from_="+15017122661") - - values = {'To': "+15558675310", 'From': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/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/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="active") - - values = {'Status': "active", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": {}, - "contact_sid": "FCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+14155555555", - "status": "ended", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": "2017-11-06T12:00:00Z", - "links": { - "steps": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="active") - - 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 bcaf692bcb..0000000000 --- a/tests/integration/studio/v1/test_flow.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "executions": "https://studio.twilio.com/v1/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions" - } - } - ''' - )) - - actual = self.client.studio.v1.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v1.flows("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("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/studio/v2/__init__.py b/tests/integration/studio/v2/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v2/flow/__init__.py b/tests/integration/studio/v2/flow/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v2/flow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v2/flow/execution/__init__.py b/tests/integration/studio/v2/flow/execution/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v2/flow/execution/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v2/flow/execution/execution_step/__init__.py b/tests/integration/studio/v2/flow/execution/execution_step/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/studio/v2/flow/execution/execution_step/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/studio/v2/flow/execution/execution_step/test_execution_step_context.py b/tests/integration/studio/v2/flow/execution/execution_step/test_execution_step_context.py deleted file mode 100644 index 2125f55712..0000000000 --- a/tests/integration/studio/v2/flow/execution/execution_step/test_execution_step_context.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionStepContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "step_sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .step_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/flow/execution/test_execution_context.py b/tests/integration/studio/v2/flow/execution/test_execution_context.py deleted file mode 100644 index be41334927..0000000000 --- a/tests/integration/studio/v2/flow/execution/test_execution_context.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionContextTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .execution_context().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Context', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": { - "foo": "bar" - }, - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .execution_context().fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/flow/execution/test_execution_step.py b/tests/integration/studio/v2/flow/execution/test_execution_step.py deleted file mode 100644 index b3ca10e2af..0000000000 --- a/tests/integration/studio/v2/flow/execution/test_execution_step.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionStepTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/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/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps?PageSize=50&Page=0", - "page_size": 50, - "key": "steps" - }, - "steps": [] - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Steps/FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "execution_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/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "step_context": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps/FTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .steps("FTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/flow/test_execution.py b/tests/integration/studio/v2/flow/test_execution.py deleted file mode 100644 index 5662fee112..0000000000 --- a/tests/integration/studio/v2/flow/test_execution.py +++ /dev/null @@ -1,197 +0,0 @@ -# coding=utf-8 -r""" -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 ExecutionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions', - )) - - 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/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions?PageSize=50&Page=0", - "page_size": 50, - "key": "executions" - }, - "executions": [] - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "contact_channel_address": "+14155555555", - "status": "ended", - "context": {}, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "steps": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.create(to="+15558675310", from_="+15017122661") - - values = {'To': "+15558675310", 'From': "+15017122661", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": {}, - "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/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions.create(to="+15558675310", from_="+15017122661") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="active") - - values = {'Status': "active", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions/FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "flow_sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "context": {}, - "contact_channel_address": "+14155555555", - "status": "ended", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": "2017-11-06T12:00:00Z", - "links": { - "steps": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Steps", - "execution_context": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions/FNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Context" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .executions("FNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="active") - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/flow/test_flow_revision.py b/tests/integration/studio/v2/flow/test_flow_revision.py deleted file mode 100644 index 91e77d5476..0000000000 --- a/tests/integration/studio/v2/flow/test_flow_revision.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -r""" -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 FlowRevisionTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .revisions.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Revisions', - )) - - 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/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions?PageSize=50&Page=0", - "page_size": 50, - "key": "revisions" - }, - "revisions": [ - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test Flow", - "status": "published", - "revision": 1, - "definition": null, - "commit_message": null, - "valid": null, - "errors": null, - "date_created": "2017-11-06T12:00:00Z", - "date_updated": "2017-11-06T12:00:00Z", - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions/1" - } - ] - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .revisions.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .revisions("revision").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Revisions/revision', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "definition": { - "initial_state": "Trigger" - }, - "friendly_name": "Test Flow", - "status": "published", - "revision": 1, - "commit_message": null, - "valid": true, - "errors": [], - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions/1" - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .revisions("revision").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/flow/test_test_user.py b/tests/integration/studio/v2/flow/test_test_user.py deleted file mode 100644 index ffed686725..0000000000 --- a/tests/integration/studio/v2/flow/test_test_user.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -r""" -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 FlowTestUserTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .test_users().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TestUsers', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "test_users": [ - "user1", - "user2" - ], - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers" - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .test_users().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .test_users().update(test_users=['test_users']) - - values = {'TestUsers': serialize.map(['test_users'], lambda e: e), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TestUsers', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "test_users": [ - "user1", - "user2" - ], - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers" - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .test_users().update(test_users=['test_users']) - - self.assertIsNotNone(actual) diff --git a/tests/integration/studio/v2/test_flow.py b/tests/integration/studio/v2/test_flow.py deleted file mode 100644 index 38edbabc54..0000000000 --- a/tests/integration/studio/v2/test_flow.py +++ /dev/null @@ -1,234 +0,0 @@ -# coding=utf-8 -r""" -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 FlowTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows.create(friendly_name="friendly_name", status="draft", definition={}) - - values = {'FriendlyName': "friendly_name", 'Status': "draft", 'Definition': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "definition": { - "initial_state": "Trigger" - }, - "friendly_name": "Test Flow", - "status": "published", - "revision": 1, - "commit_message": null, - "valid": true, - "errors": [], - "warnings": [], - "webhook_url": "http://webhooks.twilio.com/v1/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "test_users": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers", - "revisions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions", - "executions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions" - } - } - ''' - )) - - actual = self.client.studio.v2.flows.create(friendly_name="friendly_name", status="draft", definition={}) - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="draft") - - values = {'Status': "draft", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "definition": { - "initial_state": "Trigger" - }, - "friendly_name": "Test Flow", - "status": "published", - "revision": 1, - "commit_message": null, - "valid": true, - "errors": [], - "warnings": [], - "webhook_url": "http://webhooks.twilio.com/v1/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": "2017-11-06T12:00:00Z", - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "test_users": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers", - "revisions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions", - "executions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="draft") - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/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/v2/Flows?PageSize=50&Page=0", - "page": 0, - "first_page_url": "https://studio.twilio.com/v2/Flows?PageSize=50&Page=0", - "page_size": 50, - "key": "flows" - }, - "flows": [ - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test Flow", - "status": "published", - "revision": 1, - "definition": null, - "commit_message": null, - "valid": null, - "errors": null, - "warnings": null, - "webhook_url": "http://webhooks.twilio.com/v1/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": "2017-11-06T12:00:00Z", - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "test_users": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers", - "revisions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions", - "executions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions" - } - } - ] - } - ''' - )) - - actual = self.client.studio.v2.flows.list() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Test Flow", - "definition": { - "initial_state": "Trigger" - }, - "status": "published", - "revision": 1, - "commit_message": "commit", - "valid": true, - "errors": [], - "warnings": [], - "webhook_url": "http://webhooks.twilio.com/v1/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2017-11-06T12:00:00Z", - "date_updated": null, - "url": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "test_users": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TestUsers", - "revisions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Revisions", - "executions": "https://studio.twilio.com/v2/Flows/FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Executions" - } - } - ''' - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://studio.twilio.com/v2/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.studio.v2.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/studio/v2/test_flow_validate.py b/tests/integration/studio/v2/test_flow_validate.py deleted file mode 100644 index d63d58c93d..0000000000 --- a/tests/integration/studio/v2/test_flow_validate.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -r""" -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 FlowValidateTestCase(IntegrationTestCase): - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.studio.v2.flow_validate.update(friendly_name="friendly_name", status="draft", definition={}) - - values = {'FriendlyName': "friendly_name", 'Status': "draft", 'Definition': serialize.object({}), } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://studio.twilio.com/v2/Flows/Validate', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "valid": true - } - ''' - )) - - actual = self.client.studio.v2.flow_validate.update(friendly_name="friendly_name", status="draft", definition={}) - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/__init__.py b/tests/integration/supersim/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/supersim/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/supersim/v1/__init__.py b/tests/integration/supersim/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/supersim/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/supersim/v1/network_access_profile/__init__.py b/tests/integration/supersim/v1/network_access_profile/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/supersim/v1/network_access_profile/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/supersim/v1/network_access_profile/test_network_access_profile_network.py b/tests/integration/supersim/v1/network_access_profile/test_network_access_profile_network.py deleted file mode 100644 index 1a6d5ba612..0000000000 --- a/tests/integration/supersim/v1/network_access_profile/test_network_access_profile_network.py +++ /dev/null @@ -1,165 +0,0 @@ -# coding=utf-8 -r""" -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 NetworkAccessProfileNetworkTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Networks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks?PageSize=50&Page=0", - "key": "networks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks?PageSize=50&Page=0" - }, - "networks": [ - { - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "AT&T", - "iso_country": "us", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks.list() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks.create(network="HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Network': "HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Networks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "AT&T", - "iso_country": "us", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks.create(network="HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Networks/HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Networks/HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "AT&T", - "iso_country": "us", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_command.py b/tests/integration/supersim/v1/test_command.py deleted file mode 100644 index 47bc6233b1..0000000000 --- a/tests/integration/supersim/v1/test_command.py +++ /dev/null @@ -1,175 +0,0 @@ -# coding=utf-8 -r""" -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_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.commands.create(sim="HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", command="command") - - values = {'Sim': "HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 'Command': "command", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/Commands', - data=values, - )) - - def test_create_command_minimal_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "direction": "to_sim", - "url": "https://supersim.twilio.com/v1/Commands/HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.commands.create(sim="HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", command="command") - - self.assertIsNotNone(actual) - - def test_create_command_full_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "direction": "to_sim", - "url": "https://supersim.twilio.com/v1/Commands/HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.commands.create(sim="HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", command="command") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.commands("HCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Commands/HCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "content of the command", - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "direction": "to_sim", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Commands/HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.commands("HCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.commands.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Commands', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Commands?Status=queued&Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Commands?Status=queued&Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.commands.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Commands?Status=queued&Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "commands", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Commands?Status=queued&Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - }, - "commands": [ - { - "sid": "HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "content of the command", - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "direction": "from_sim", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Commands/HCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.commands.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_fleet.py b/tests/integration/supersim/v1/test_fleet.py deleted file mode 100644 index 8e578cb9bb..0000000000 --- a/tests/integration/supersim/v1/test_fleet.py +++ /dev/null @@ -1,202 +0,0 @@ -# coding=utf-8 -r""" -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_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.fleets.create(network_access_profile="HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'NetworkAccessProfile': "HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/Fleets', - data=values, - )) - - 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": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-07-30T20:00:00Z", - "commands_enabled": true, - "commands_method": "GET", - "commands_url": "https://google.com", - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.fleets.create(network_access_profile="HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.fleets("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Fleets/HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - 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": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-07-30T20:00:00Z", - "commands_enabled": true, - "commands_method": "POST", - "commands_url": null, - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.fleets("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.fleets.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Fleets', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "fleets": [], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "fleets", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.fleets.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "fleets", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - }, - "fleets": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "Pilot Fleet", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "payg", - "date_created": "2019-10-15T20:00:00Z", - "date_updated": "2019-10-15T20:00:00Z", - "commands_enabled": true, - "commands_method": "POST", - "commands_url": null, - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.fleets.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.fleets("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/Fleets/HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique_name", - "data_enabled": true, - "data_limit": 1000, - "data_metering": "payg", - "date_created": "2019-10-15T20:00:00Z", - "date_updated": "2019-10-15T20:00:00Z", - "commands_enabled": true, - "commands_method": "POST", - "commands_url": null, - "network_access_profile_sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.fleets("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_network.py b/tests/integration/supersim/v1/test_network.py deleted file mode 100644 index 7de80b5c20..0000000000 --- a/tests/integration/supersim/v1/test_network.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -r""" -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 NetworkTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Networks/HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "friendly_name": "AT&T", - "iso_country": "US", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.networks("HWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.networks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Networks', - )) - - def test_read_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Networks?PageSize=50&Page=0", - "key": "networks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Networks?PageSize=50&Page=0" - }, - "networks": [ - { - "friendly_name": "AT&T", - "iso_country": "US", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.networks.list() - - self.assertIsNotNone(actual) - - def test_read_with_filters_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Networks?IsoCountry=US&Mnc=410&Mcc=310&PageSize=50&Page=0", - "key": "networks", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Networks?IsoCountry=US&Mnc=410&Mcc=310&PageSize=50&Page=0" - }, - "networks": [ - { - "friendly_name": "AT&T", - "iso_country": "US", - "identifiers": [ - { - "mcc": "310", - "mnc": "410" - } - ], - "sid": "HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://supersim.twilio.com/v1/Networks/HWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.networks.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_network_access_profile.py b/tests/integration/supersim/v1/test_network_access_profile.py deleted file mode 100644 index f3b9aaf7f0..0000000000 --- a/tests/integration/supersim/v1/test_network_access_profile.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding=utf-8 -r""" -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 NetworkAccessProfileTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles', - )) - - def test_create_minimal_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "unique_name": null, - "sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-05-01T20:00:00Z", - "date_updated": "2020-05-01T20:00:00Z", - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "networks": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks" - } - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles.create() - - self.assertIsNotNone(actual) - - def test_create_with_name_and_networks_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "unique_name": "My Network Access Profile", - "sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-05-01T20:00:00Z", - "date_updated": "2020-05-01T20:00:00Z", - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "networks": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks" - } - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "My Network Access Profile", - "sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-05-01T20:00:00Z", - "date_updated": "2020-05-01T20:00:00Z", - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "networks": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks" - } - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles/HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "unique_name": "My Network Access Profile", - "sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-05-01T20:00:00Z", - "date_updated": "2020-05-01T20:00:00Z", - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "networks": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks" - } - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.network_access_profiles.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/NetworkAccessProfiles', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "network_access_profiles": [], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/NetworkAccessProfiles?PageSize=50&Page=0", - "key": "network_access_profiles", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/NetworkAccessProfiles?PageSize=50&Page=0", - "key": "network_access_profiles", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles?PageSize=50&Page=0" - }, - "network_access_profiles": [ - { - "unique_name": "My Network Access Profile", - "sid": "HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-05-01T20:00:00Z", - "date_updated": "2020-05-01T20:00:00Z", - "url": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "networks": "https://supersim.twilio.com/v1/NetworkAccessProfiles/HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Networks" - } - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.network_access_profiles.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_sim.py b/tests/integration/supersim/v1/test_sim.py deleted file mode 100644 index d3a17f600c..0000000000 --- a/tests/integration/supersim/v1/test_sim.py +++ /dev/null @@ -1,286 +0,0 @@ -# coding=utf-8 -r""" -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.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My SIM", - "status": "new", - "fleet_sid": null, - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://supersim.twilio.com/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "MySIM", - "status": "new", - "fleet_sid": null, - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_status_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": null, - "status": "scheduled", - "fleet_sid": null, - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_fleet_with_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": null, - "status": "new", - "fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_fleet_with_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": null, - "status": "new", - "fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.supersim.v1.sims("HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.supersim.v1.sims.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/Sims', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sims": [], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_read_full_by_fleet_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - }, - "sims": [ - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My SIM", - "status": "new", - "fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_read_full_by_fleet_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=MyFleet&PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Sims?Status=new&Fleet=MyFleet&PageSize=50&Page=0" - }, - "sims": [ - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My SIM", - "status": "new", - "fleet_sid": "HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.sims.list() - - self.assertIsNotNone(actual) - - def test_read_by_iccid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/Sims?Iccid=11111111111111111111&PageSize=50&Page=0", - "key": "sims", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/Sims?Iccid=11111111111111111111&PageSize=50&Page=0" - }, - "sims": [ - { - "sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "My SIM", - "status": "new", - "fleet_sid": null, - "iccid": "11111111111111111111", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://supersim.twilio.com/v1/Sims/HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.supersim.v1.sims.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/supersim/v1/test_usage_record.py b/tests/integration/supersim/v1/test_usage_record.py deleted file mode 100644 index 63d81c9018..0000000000 --- a/tests/integration/supersim/v1/test_usage_record.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding=utf-8 -r""" -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.supersim.v1.usage_records.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://supersim.twilio.com/v1/UsageRecords', - )) - - def test_read_all_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "period": { - "start_time": "2015-05-01T20:00:00Z", - "end_time": "2015-06-01T20:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": null - } - ], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0", - "key": "usage_records", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/UsageRecords?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.usage_records.list() - - self.assertIsNotNone(actual) - - def test_read_all_day_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "period": { - "start_time": "2019-05-01T00:00:00Z", - "end_time": "2019-05-03T00:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": null - }, - { - "period": { - "start_time": "2019-05-03T00:00:00Z", - "end_time": "2019-05-04T00:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": null - } - ], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=day&PageSize=50&Page=0", - "key": "usage_records", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=day&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.usage_records.list() - - self.assertIsNotNone(actual) - - def test_read_all_hour_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "period": { - "start_time": "2019-05-01T00:00:00Z", - "end_time": "2019-05-01T01:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": null - }, - { - "period": { - "start_time": "2019-05-01T01:00:00Z", - "end_time": "2019-05-01T02:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": null - } - ], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=hour&PageSize=50&Page=0", - "key": "usage_records", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/UsageRecords?Granularity=hour&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.usage_records.list() - - self.assertIsNotNone(actual) - - def test_read_day_sim_filter_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "period": { - "start_time": "2019-05-01T00:00:00Z", - "end_time": "2019-05-03T00:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "period": { - "start_time": "2019-05-03T00:00:00Z", - "end_time": "2019-05-04T00:00:00Z" - }, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "data_upload": 1000, - "data_download": 1000, - "data_total": 2000, - "sim_sid": "HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://supersim.twilio.com/v1/UsageRecords?Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0", - "key": "usage_records", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://supersim.twilio.com/v1/UsageRecords?Sim=HSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Granularity=day&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.supersim.v1.usage_records.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/sync/__init__.py b/tests/integration/sync/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/sync/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/service/document/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 0d2a073e93..0000000000 --- a/tests/integration/sync/v1/service/document/test_document_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .document_permissions("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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/service/sync_list/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 420cbee37b..0000000000 --- a/tests/integration/sync/v1/service/sync_list/test_sync_list_item.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(1).update(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Lists/ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/1', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_items(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 3cb4e66bcb..0000000000 --- a/tests/integration/sync/v1/service/sync_list/test_sync_list_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_list_permissions("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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/service/sync_map/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 08f43e9ca8..0000000000 --- a/tests/integration/sync/v1/service/sync_map/test_sync_map_item.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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?From=from&Bounds=inclusive&Order=asc&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?From=from&Bounds=inclusive&Order=asc&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("key").update(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Items/key', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_items("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 e4d85a0aa3..0000000000 --- a/tests/integration/sync/v1/service/sync_map/test_sync_map_permission.py +++ /dev/null @@ -1,189 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("identity").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("identity").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_map_permissions("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 c9fc143806..0000000000 --- a/tests/integration/sync/v1/service/sync_stream/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 6e1192eb4d..0000000000 --- a/tests/integration/sync/v1/service/sync_stream/test_stream_message.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("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 0b1ebe282b..0000000000 --- a/tests/integration/sync/v1/service/test_document.py +++ /dev/null @@ -1,239 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("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("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(if_match="if_match") - - headers = {'If-Match': "if_match", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - 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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .documents("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 e497b8bbc4..0000000000 --- a/tests/integration/sync/v1/service/test_sync_list.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_lists("ESXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("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 c880e3bf6f..0000000000 --- a/tests/integration/sync/v1/service/test_sync_map.py +++ /dev/null @@ -1,235 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_maps("MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("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 c9af8a6fab..0000000000 --- a/tests/integration/sync/v1/service/test_sync_stream.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -r""" -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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("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("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .sync_streams("TOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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("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 b7672a53cf..0000000000 --- a/tests/integration/sync/v1/test_service.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "webhooks_from_rest_enabled": false, - "reachability_webhooks_enabled": false, - "acl_enabled": false, - "reachability_debouncing_enabled": false, - "reachability_debouncing_window": 5000 - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.sync.v1.services("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("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", - "webhooks_from_rest_enabled": false, - "reachability_webhooks_enabled": false, - "acl_enabled": true, - "reachability_debouncing_enabled": false, - "reachability_debouncing_window": 5000 - } - ''' - )) - - 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", - "webhooks_from_rest_enabled": false, - "reachability_webhooks_enabled": false, - "acl_enabled": false, - "reachability_debouncing_enabled": false, - "reachability_debouncing_window": 5000 - } - ] - } - ''' - )) - - 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("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", - "webhooks_from_rest_enabled": false, - "reachability_webhooks_enabled": false, - "acl_enabled": true, - "reachability_debouncing_enabled": false, - "reachability_debouncing_window": 5000 - } - ''' - )) - - actual = self.client.sync.v1.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/taskrouter/__init__.py b/tests/integration/taskrouter/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/taskrouter/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 ea7b143306..0000000000 --- a/tests/integration/taskrouter/v1/test_workspace.py +++ /dev/null @@ -1,275 +0,0 @@ -# coding=utf-8 -r""" -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("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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("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?FriendlyName=friendly_name&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?FriendlyName=friendly_name&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?FriendlyName=friendly_name&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?FriendlyName=friendly_name&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("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("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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/workspace/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 adc500c9cc..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task/test_reservation.py +++ /dev/null @@ -1,212 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_supervise_instruction_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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 6743a5e893..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_cumulative_statistics.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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 - }, - "wait_duration_in_queue_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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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 76597c505f..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_real_time_statistics.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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, - "longest_task_waiting_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "longest_relative_task_age_in_queue": 100, - "longest_relative_task_sid_in_queue": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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 7daca815b8..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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 b75972480d..0000000000 --- a/tests/integration/taskrouter/v1/workspace/task_queue/test_task_queues_statistics.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -r""" -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("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?FriendlyName=friendly_name&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-02T00%3A00%3A00Z&Minutes=1&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?FriendlyName=friendly_name&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-02T00%3A00%3A00Z&Minutes=1&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": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("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?FriendlyName=friendly_name&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-02T00%3A00%3A00Z&Minutes=1&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?FriendlyName=friendly_name&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-02T00%3A00%3A00Z&Minutes=1&PageSize=50&Page=0" - }, - "task_queues_statistics": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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 ab7ba8b2c4..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_activity.py +++ /dev/null @@ -1,216 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .activities("WAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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("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("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("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("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 62317a4371..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_event.py +++ /dev/null @@ -1,158 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events("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", - "worker_time_in_previous_activity_ms": "26123", - "workspace_name": "WorkspaceName", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "event_date": "2015-02-07T00:32:41Z", - "event_date_ms": 987654321111, - "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", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .events("EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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", - "worker_time_in_previous_activity_ms": "26123", - "workspace_name": "WorkspaceName", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "event_date": "2015-02-07T00:32:41Z", - "event_date_ms": 987654321111, - "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", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-03T00%3A00%3A00Z&WorkerSid=WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EventType=reservation.created&TaskSid=WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&WorkflowSid=WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ReservationSid=WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-03T00%3A00%3A00Z&WorkerSid=WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EventType=reservation.created&TaskSid=WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&WorkflowSid=WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ReservationSid=WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-03T00%3A00%3A00Z&WorkerSid=WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EventType=reservation.created&TaskSid=WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&WorkflowSid=WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ReservationSid=WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&StartDate=2008-01-02T00%3A00%3A00Z&EndDate=2008-01-03T00%3A00%3A00Z&WorkerSid=WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&EventType=reservation.created&TaskSid=WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&WorkflowSid=WWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ReservationSid=WRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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 99cf478cca..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task.py +++ /dev/null @@ -1,307 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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", - "task_queue_entered_date": "2014-05-14T18:50:02Z", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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", - "task_queue_entered_date": "2014-05-14T18:50:02Z", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .tasks("WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending%2Creserved&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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending%2Creserved&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", - "task_queue_entered_date": "2014-05-14T14:26:54Z", - "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("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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending&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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending&PageSize=50&Page=0" - }, - "tasks": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending&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?TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&Priority=1&TaskQueueName=task_queue_name&WorkflowName=workflow_name&WorkflowSid=WFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&AssignmentStatus=pending&PageSize=50&Page=0" - }, - "tasks": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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("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", - "task_queue_entered_date": null, - "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("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 c72a4d2377..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task_channel.py +++ /dev/null @@ -1,293 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels/TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "friendly_name": "Default", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_optimized_routing": true, - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "friendly_name": "Default", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_optimized_routing": false, - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "friendly_name": "Default", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "default", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_optimized_routing": true, - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ], - "meta": { - "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels?PageSize=50&Page=0", - "key": "channels", - "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("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", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels/TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Default", - "unique_name": "default", - "date_created": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_optimized_routing": true, - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_unique_name_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Default", - "unique_name": "default", - "date_created": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "channel_optimized_routing": true, - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels/TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_sid_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_delete_unique_name_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels("TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.create(friendly_name="friendly_name", unique_name="unique_name") - - values = {'FriendlyName': "friendly_name", 'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskChannels', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "Outbound Voice", - "unique_name": "ovoice", - "date_created": "2016-04-14T17:35:54Z", - "date_updated": "2016-04-14T17:35:54Z", - "channel_optimized_routing": true, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskChannels/TCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "workspace": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_channels.create(friendly_name="friendly_name", unique_name="unique_name") - - 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 53db496499..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_task_queue.py +++ /dev/null @@ -1,274 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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?EvaluateWorkerAttributes=evaluate_worker_attributes&FriendlyName=friendly_name&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?EvaluateWorkerAttributes=evaluate_worker_attributes&FriendlyName=friendly_name&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("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?EvaluateWorkerAttributes=evaluate_worker_attributes&FriendlyName=friendly_name&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?EvaluateWorkerAttributes=evaluate_worker_attributes&FriendlyName=friendly_name&PageSize=50&Page=0" - }, - "task_queues": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - 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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues.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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .task_queues("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 541ecc038f..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_worker.py +++ /dev/null @@ -1,274 +0,0 @@ -# coding=utf-8 -r""" -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("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?Available=available&TargetWorkersExpression=target_workers_expression&TaskQueueName=task_queue_name&ActivityName=activity_name&ActivitySid=WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&FriendlyName=friendly_name&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers?Available=available&TargetWorkersExpression=target_workers_expression&TaskQueueName=task_queue_name&ActivityName=activity_name&ActivitySid=WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&FriendlyName=friendly_name&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("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?Available=available&TargetWorkersExpression=target_workers_expression&TaskQueueName=task_queue_name&ActivityName=activity_name&ActivitySid=WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&FriendlyName=friendly_name&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?Available=available&TargetWorkersExpression=target_workers_expression&TaskQueueName=task_queue_name&ActivityName=activity_name&ActivitySid=WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&TaskQueueSid=WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&FriendlyName=friendly_name&PageSize=50&Page=0" - }, - "workers": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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("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("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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 918ae0ef56..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workflow.py +++ /dev/null @@ -1,250 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("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?FriendlyName=friendly_name&PageSize=50&Page=0", - "key": "workflows", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?FriendlyName=friendly_name&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("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?FriendlyName=friendly_name&PageSize=50&Page=0", - "key": "workflows", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workflows?FriendlyName=friendly_name&PageSize=50&Page=0" - }, - "workflows": [] - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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("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("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 9b842dbcc4..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_cumulative_statistics.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 603b86ce4d..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_real_time_statistics.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "longest_task_waiting_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "total_workers": 100, - "total_tasks": 100, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "tasks_by_status": {} - } - ''' - )) - - actual = self.client.taskrouter.v1.workspaces("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 fecad115d4..0000000000 --- a/tests/integration/taskrouter/v1/workspace/test_workspace_statistics.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding=utf-8 -r""" -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("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": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 afebb0b755..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_reservation.py +++ /dev/null @@ -1,182 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .reservations("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 81493c4036..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_worker_channel.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels("WCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.taskrouter.v1.workspaces("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .worker_channels("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 72fee34381..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_worker_statistics.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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 a498afe867..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_cumulative_statistics.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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 9ce3404e96..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_real_time_statistics.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workers("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 3bb4e51fe5..0000000000 --- a/tests/integration/taskrouter/v1/workspace/worker/test_workers_statistics.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding=utf-8 -r""" -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("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("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 c9fc143806..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 aeeb3b2d1b..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_cumulative_statistics.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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 c0e27322ec..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_real_time_statistics.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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, - "longest_task_waiting_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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 4b7c163a30..0000000000 --- a/tests/integration/taskrouter/v1/workspace/workflow/test_workflow_statistics.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding=utf-8 -r""" -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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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("WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .workflows("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 c9fc143806..0000000000 --- a/tests/integration/trunking/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/trunking/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 4ebc3bb258..0000000000 --- a/tests/integration/trunking/v1/test_trunk.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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, - "cnam_lookup_enabled": 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": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").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": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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, - "cnam_lookup_enabled": 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": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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=50&Page=0", - "url": "https://trunking.twilio.com/v1/Trunks?PageSize=50&Page=0", - "page_size": 50, - "key": "trunks", - "next_page_url": null, - "page": 0, - "previous_page_url": null - }, - "trunks": [ - { - "sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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, - "cnam_lookup_enabled": 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": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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=50&Page=0", - "url": "https://trunking.twilio.com/v1/Trunks?PageSize=50&Page=0", - "page_size": 50, - "key": "trunks", - "next_page_url": null, - "page": 0, - "previous_page_url": null - }, - "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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "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, - "cnam_lookup_enabled": 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": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "origination_urls": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls", - "credential_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists", - "ip_access_control_lists": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists", - "phone_numbers": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").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 c9fc143806..0000000000 --- a/tests/integration/trunking/v1/trunk/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 ff3754fed2..0000000000 --- a/tests/integration/trunking/v1/trunk/test_credential_list.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -r""" -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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-04-28T00:10:23Z", - "date_updated": "2018-04-28T00:10:23Z", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists/CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists("CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.create(credential_list_sid="CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'CredentialListSid': "CLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-02T17:29:30Z", - "date_updated": "2018-05-02T17:29:30Z", - "friendly_name": "friendly_name", - "sid": "CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/CredentialLists/CLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .credentials_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/CredentialLists', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "credential_lists": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-04-27T22:02:11Z", - "date_updated": "2018-04-27T22:02:11Z", - "friendly_name": "friendly_name", - "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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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 ee2e456c61..0000000000 --- a/tests/integration/trunking/v1/trunk/test_ip_access_control_list.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -r""" -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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-02T17:29:34Z", - "date_updated": "2018-05-02T17:29:34Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists/ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists("ALXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IpAccessControlLists', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-04-30T20:59:06Z", - "date_updated": "2018-04-30T20:59:06Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .ip_access_control_lists.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0", - "key": "ip_access_control_lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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": "2018-05-02T17:29:34Z", - "date_updated": "2018-05-02T17:29:34Z", - "friendly_name": "friendly_name", - "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0", - "key": "ip_access_control_lists", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAccessControlLists?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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 42cbf354b5..0000000000 --- a/tests/integration/trunking/v1/trunk/test_origination_url.py +++ /dev/null @@ -1,232 +0,0 @@ -# coding=utf-8 -r""" -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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 1, - "date_updated": "2018-05-07T20:20:46Z", - "enabled": false, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-07T20:20:46Z", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "weight": 1, - "date_updated": "2018-05-07T20:50:58Z", - "enabled": true, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-07T20:50:58Z", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=50&Page=0", - "key": "origination_urls", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=50&Page=0" - }, - "origination_urls": [ - { - "weight": 1, - "date_updated": "2018-05-09T20:47:35Z", - "enabled": true, - "friendly_name": "friendly_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 1, - "sip_url": "sip://sip-box.com:1234", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-09T20:47:35Z", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=50&Page=0", - "key": "origination_urls", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=50&Page=0" - }, - "origination_urls": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OriginationUrls/OUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "weight": 2, - "date_updated": "2018-05-07T20:50:58Z", - "enabled": false, - "friendly_name": "updated_name", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "priority": 2, - "sip_url": "sip://sip-updated.com:4321", - "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2018-05-07T20:50:58Z", - "trunk_sid": "TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .origination_urls("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 38c93c212d..0000000000 --- a/tests/integration/trunking/v1/trunk/test_phone_number.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -r""" -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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.create(phone_number_sid="PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'PhoneNumberSid': "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://trunking.twilio.com/v1/Trunks/TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/PhoneNumbers', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "first_page_url": "https://trunking.twilio.com/v1/Trunks/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .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/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/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/TKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/PhoneNumbers?PageSize=1&Page=0" - }, - "phone_numbers": [] - } - ''' - )) - - actual = self.client.trunking.v1.trunks("TKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .phone_numbers.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/__init__.py b/tests/integration/verify/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/verify/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/verify/v2/__init__.py b/tests/integration/verify/v2/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/verify/v2/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/verify/v2/service/__init__.py b/tests/integration/verify/v2/service/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/verify/v2/service/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/verify/v2/service/entity/__init__.py b/tests/integration/verify/v2/service/entity/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/verify/v2/service/entity/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/verify/v2/service/entity/test_challenge.py b/tests/integration/verify/v2/service/entity/test_challenge.py deleted file mode 100644 index 460cb08e95..0000000000 --- a/tests/integration/verify/v2/service/entity/test_challenge.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -r""" -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 ChallengeTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges.create(factor_sid="YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", twilio_sandbox_mode="twilio_sandbox_mode") - - values = {'FactorSid': "YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Challenges', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Challenges', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "factor_sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_responded": "2015-07-30T20:00:00Z", - "expiration_date": "2015-07-30T20:00:00Z", - "status": "pending", - "responded_reason": "none", - "details": "Hi! Mr. John Doe, would you like to sign up?", - "hidden_details": "Hidden details about the sign up", - "factor_type": "push", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges.create(factor_sid="YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges("YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Challenges/YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_fetch_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "factor_sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_responded": "2015-07-30T20:00:00Z", - "expiration_date": "2015-07-30T20:00:00Z", - "status": "pending", - "responded_reason": "none", - "details": "details", - "hidden_details": "hidden_details", - "factor_type": "push", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges("YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges.list(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Challenges', - headers=headers, - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "challenges": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges?PageSize=50&Page=0", - "next_page_url": null, - "key": "challenges" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "challenges": [ - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "factor_sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_responded": "2015-07-30T20:00:00Z", - "expiration_date": "2015-07-30T20:00:00Z", - "status": "pending", - "responded_reason": "none", - "details": "details", - "hidden_details": "hidden_details", - "factor_type": "push", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges?PageSize=50&Page=0", - "next_page_url": null, - "key": "challenges" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges("YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Challenges/YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_verify_sid_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "factor_sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "date_responded": "2015-07-30T20:00:00Z", - "expiration_date": "2015-07-30T20:00:00Z", - "status": "approved", - "responded_reason": "none", - "details": "Hi! Mr. John Doe, would you like to sign up?", - "hidden_details": "Hidden details about the sign up", - "factor_type": "push", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .challenges("YCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/entity/test_factor.py b/tests/integration/verify/v2/service/entity/test_factor.py deleted file mode 100644 index d1330eb3b1..0000000000 --- a/tests/integration/verify/v2/service/entity/test_factor.py +++ /dev/null @@ -1,280 +0,0 @@ -# coding=utf-8 -r""" -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 FactorTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.create(binding="binding", friendly_name="friendly_name", factor_type="push", config="config", twilio_sandbox_mode="twilio_sandbox_mode", authorization="authorization") - - values = { - 'Binding': "binding", - 'FriendlyName': "friendly_name", - 'FactorType': "push", - 'Config': "config", - } - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", 'Authorization': "authorization", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "status": "unverified", - "factor_type": "push", - "config": { - "sdk_version": "1.0", - "app_id": "com.authy.authy", - "notification_platform": "fcm", - "notification_token": "test_token" - }, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.create(binding="binding", friendly_name="friendly_name", factor_type="push", config="config") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "status": "unverified", - "factor_type": "push", - "config": { - "sdk_version": "1.0", - "app_id": "com.authy.authy", - "notification_platform": "fcm", - "notification_token": "test_token" - }, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.list(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors', - headers=headers, - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "factors": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "next_page_url": null, - "key": "factors" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "factors": [ - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "status": "unverified", - "factor_type": "push", - "config": { - "sdk_version": "1.0", - "app_id": "com.authy.authy", - "notification_platform": "fcm", - "notification_token": "test_token" - }, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors?PageSize=50&Page=0", - "next_page_url": null, - "key": "factors" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity/Factors/YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - headers=headers, - )) - - def test_verify_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "entity_sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "friendly_name": "friendly_name", - "status": "verified", - "factor_type": "push", - "config": { - "sdk_version": "1.0", - "app_id": "com.authy.authy", - "notification_platform": "fcm", - "notification_token": "test_token" - }, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors/YFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity") \ - .factors("YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/rate_limit/__init__.py b/tests/integration/verify/v2/service/rate_limit/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/verify/v2/service/rate_limit/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/verify/v2/service/rate_limit/test_bucket.py b/tests/integration/verify/v2/service/rate_limit/test_bucket.py deleted file mode 100644 index f70af7f247..0000000000 --- a/tests/integration/verify/v2/service/rate_limit/test_bucket.py +++ /dev/null @@ -1,229 +0,0 @@ -# coding=utf-8 -r""" -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 BucketTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets.create(max=1, interval=1) - - values = {'Max': 1, 'Interval': 1, } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Buckets', - data=values, - )) - - def test_create_bucket_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "rate_limit_sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "max": 5, - "interval": 60, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets/BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets.create(max=1, interval=1) - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Buckets/BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_bucket_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "rate_limit_sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "max": 5, - "interval": 60, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets/BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Buckets/BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_bucket_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "rate_limit_sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "max": 5, - "interval": 60, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets/BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Buckets', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "buckets": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets?PageSize=50&Page=0", - "next_page_url": null, - "key": "buckets" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "buckets": [ - { - "sid": "BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "rate_limit_sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "max": 5, - "interval": 60, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets/BLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets?PageSize=50&Page=0", - "next_page_url": null, - "key": "buckets" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Buckets/BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .buckets("BLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/verify/v2/service/test_access_token.py b/tests/integration/verify/v2/service/test_access_token.py deleted file mode 100644 index 63ead4be9c..0000000000 --- a/tests/integration/verify/v2/service/test_access_token.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -r""" -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 AccessTokenTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .access_tokens.create(identity="identity", factor_type="push") - - values = {'Identity': "identity", 'FactorType': "push", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AccessTokens', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "token": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .access_tokens.create(identity="identity", factor_type="push") - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/test_entity.py b/tests/integration/verify/v2/service/test_entity.py deleted file mode 100644 index c17c24432d..0000000000 --- a/tests/integration/verify/v2/service/test_entity.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding=utf-8 -r""" -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 EntityTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.create(identity="identity", twilio_sandbox_mode="twilio_sandbox_mode") - - values = {'Identity': "identity", } - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities', - headers=headers, - )) - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors", - "challenges": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.create(identity="identity") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").delete(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity', - headers=headers, - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").fetch(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/identity', - headers=headers, - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors", - "challenges": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities("identity").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.list(twilio_sandbox_mode="twilio_sandbox_mode") - - headers = {'Twilio-Sandbox-Mode': "twilio_sandbox_mode", } - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities', - headers=headers, - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "entities": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "next_page_url": null, - "key": "entities" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "entities": [ - { - "sid": "YEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "identity": "ff483d1ff591898a9942916050d2ca3f", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f", - "links": { - "factors": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Factors", - "challenges": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities?PageSize=50&Page=0", - "next_page_url": null, - "key": "entities" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .entities.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/test_messaging_configuration.py b/tests/integration/verify/v2/service/test_messaging_configuration.py deleted file mode 100644 index 9f1411aae4..0000000000 --- a/tests/integration/verify/v2/service/test_messaging_configuration.py +++ /dev/null @@ -1,213 +0,0 @@ -# coding=utf-8 -r""" -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 MessagingConfigurationTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations.create(country="country", messaging_service_sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'Country': "country", 'MessagingServiceSid': "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "country": "CA", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations.create(country="country", messaging_service_sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").update(messaging_service_sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'MessagingServiceSid': "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "country": "CA", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").update(messaging_service_sid="MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "country": "CA", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "messaging_configurations": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0", - "next_page_url": null, - "key": "messaging_configurations" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "messaging_configurations": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "country": "CA", - "messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations/CA" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations?PageSize=50&Page=0", - "next_page_url": null, - "key": "messaging_configurations" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/MessagingConfigurations/country', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .messaging_configurations("country").delete() - - self.assertTrue(actual) diff --git a/tests/integration/verify/v2/service/test_rate_limit.py b/tests/integration/verify/v2/service/test_rate_limit.py deleted file mode 100644 index 9cfe569bdd..0000000000 --- a/tests/integration/verify/v2/service/test_rate_limit.py +++ /dev/null @@ -1,202 +0,0 @@ -# coding=utf-8 -r""" -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 RateLimitTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits.create(unique_name="unique_name") - - values = {'UniqueName': "unique_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits', - data=values, - )) - - def test_create_rate_limit_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique.name", - "description": "Description", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "buckets": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits.create(unique_name="unique_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_rate_limit_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique.name", - "description": "Description", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "buckets": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_rate_limit_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique.name", - "description": "Description", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "buckets": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits', - )) - - def test_read_all_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "rate_limits", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits?PageSize=50&Page=0" - }, - "rate_limits": [ - { - "sid": "RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "unique_name": "unique.name", - "description": "Description", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "buckets": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits/RKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Buckets" - } - } - ] - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/RateLimits/RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .rate_limits("RKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/verify/v2/service/test_verification.py b/tests/integration/verify/v2/service/test_verification.py deleted file mode 100644 index b0c7aa43a1..0000000000 --- a/tests/integration/verify/v2/service/test_verification.py +++ /dev/null @@ -1,309 +0,0 @@ -# coding=utf-8 -r""" -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.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - values = {'To': "to", 'Channel': "channel", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/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": "+15017122661", - "channel": "sms", - "status": "pending", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": "Carrier Name", - "mobile_country_code": "310", - "mobile_network_code": "150", - "type": "mobile" - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "SMS", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - self.assertIsNotNone(actual) - - def test_create_verification_email_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "mail@email.com", - "channel": "email", - "status": "pending", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": null, - "mobile_country_code": null, - "mobile_network_code": null, - "type": null - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "EMAIL", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - self.assertIsNotNone(actual) - - def test_create_verification_with_rate_limits_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+15017122661", - "channel": "sms", - "status": "pending", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": "Carrier Name", - "mobile_country_code": "310", - "mobile_network_code": "150", - "type": "mobile" - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "SMS", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications.create(to="to", channel="channel") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications("sid").update(status="canceled") - - values = {'Status': "canceled", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Verifications/sid', - data=values, - )) - - def test_update_verification_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+15017122661", - "channel": "sms", - "status": "canceled", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": "Carrier Name", - "mobile_country_code": "310", - "mobile_network_code": "150", - "type": "mobile" - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "SMS", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications("sid").update(status="canceled") - - self.assertIsNotNone(actual) - - def test_approve_verification_with_pn_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+15017122661", - "channel": "sms", - "status": "approved", - "valid": true, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": "Carrier Name", - "mobile_country_code": "310", - "mobile_network_code": "150", - "type": "mobile" - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "SMS", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications("sid").update(status="canceled") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications("sid").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Verifications/sid', - )) - - def test_fetch_verification_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "+15017122661", - "channel": "sms", - "status": "pending", - "valid": false, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "lookup": { - "carrier": { - "error_code": null, - "name": "Carrier Name", - "mobile_country_code": "310", - "mobile_network_code": "150", - "type": "mobile" - } - }, - "amount": null, - "payee": null, - "send_code_attempts": [ - { - "time": "2015-07-30T20:00:00Z", - "channel": "SMS", - "channel_id": null - } - ], - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verifications("sid").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/test_verification_check.py b/tests/integration/verify/v2/service/test_verification_check.py deleted file mode 100644 index 9916ade15a..0000000000 --- a/tests/integration/verify/v2/service/test_verification_check.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -r""" -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.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verification_checks.create(code="code") - - values = {'Code': "code", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/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": "+15017122661", - "channel": "sms", - "status": "approved", - "valid": true, - "amount": null, - "payee": null, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verification_checks.create(code="code") - - self.assertIsNotNone(actual) - - def test_email_verification_checks_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "to": "recipient@foo.com", - "channel": "email", - "status": "approved", - "valid": true, - "amount": null, - "payee": null, - "date_created": "2020-01-30T20:00:00Z", - "date_updated": "2020-01-30T20:00:00Z" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .verification_checks.create(code="code") - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/service/test_webhook.py b/tests/integration/verify/v2/service/test_webhook.py deleted file mode 100644 index 204dfe2807..0000000000 --- a/tests/integration/verify/v2/service/test_webhook.py +++ /dev/null @@ -1,243 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(friendly_name="friendly_name", event_types=['event_types'], webhook_url="webhook_url") - - values = { - 'FriendlyName': "friendly_name", - 'EventTypes': serialize.map(['event_types'], lambda e: e), - 'WebhookUrl': "webhook_url", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "event_types": [ - "factor.deleted", - "factor.verified" - ], - "webhook_method": "POST", - "webhook_url": "https://owlbank.twilio.com", - "status": "enabled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.create(friendly_name="friendly_name", event_types=['event_types'], webhook_url="webhook_url") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "event_types": [ - "factor.deleted", - "factor.verified" - ], - "webhook_method": "POST", - "webhook_url": "https://owlbank.twilio.com", - "status": "disabled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "event_types": [ - "factor.deleted", - "factor.verified" - ], - "webhook_method": "POST", - "webhook_url": "https://owlbank.twilio.com", - "status": "enabled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks("YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "webhooks": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "next_page_url": null, - "key": "webhooks" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "webhooks": [ - { - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks/YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "YWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "event_types": [ - "factor.deleted", - "factor.verified" - ], - "webhook_method": "POST", - "webhook_url": "https://owlbank.twilio.com", - "status": "enabled", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks?PageSize=50&Page=0", - "next_page_url": null, - "key": "webhooks" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .webhooks.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/test_form.py b/tests/integration/verify/v2/test_form.py deleted file mode 100644 index a14604c17b..0000000000 --- a/tests/integration/verify/v2/test_form.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding=utf-8 -r""" -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 FormTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.forms("form-push").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Forms/form-push', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "form_type": "form-push", - "forms": { - "create_factor": {}, - "verify_factor": {}, - "create_challenge": {} - }, - "form_meta": {}, - "url": "https://verify.twilio.com/v2/Forms/form-push" - } - ''' - )) - - actual = self.client.verify.v2.forms("form-push").fetch() - - self.assertIsNotNone(actual) diff --git a/tests/integration/verify/v2/test_service.py b/tests/integration/verify/v2/test_service.py deleted file mode 100644 index 5e6eb5e028..0000000000 --- a/tests/integration/verify/v2/test_service.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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.verify.v2.services.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services', - data=values, - )) - - def test_create_record_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "code_length": 4, - "lookup_enabled": false, - "psd2_enabled": false, - "skip_sms_to_landlines": false, - "dtmf_input_required": false, - "tts_name": "name", - "mailer_sid": "MDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "do_not_share_warning_enabled": false, - "custom_code_enabled": true, - "push": { - "include_date": true, - "notify_service_sid": null - }, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications", - "rate_limits": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits", - "messaging_configurations": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations", - "entities": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities", - "webhooks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "access_tokens": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AccessTokens" - } - } - ''' - )) - - actual = self.client.verify.v2.services.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_record_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "code_length": 4, - "lookup_enabled": false, - "psd2_enabled": false, - "skip_sms_to_landlines": false, - "dtmf_input_required": false, - "tts_name": "name", - "mailer_sid": "MDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "do_not_share_warning_enabled": false, - "custom_code_enabled": true, - "push": { - "include_date": true, - "notify_service_sid": null - }, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications", - "rate_limits": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits", - "messaging_configurations": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations", - "entities": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities", - "webhooks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "access_tokens": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AccessTokens" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://verify.twilio.com/v2/Services', - )) - - def test_read_all_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://verify.twilio.com/v2/Services?PageSize=50&Page=0", - "previous_page_url": null, - "next_page_url": null, - "key": "services", - "url": "https://verify.twilio.com/v2/Services?PageSize=50&Page=0" - }, - "services": [ - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "code_length": 4, - "lookup_enabled": false, - "psd2_enabled": false, - "skip_sms_to_landlines": false, - "dtmf_input_required": false, - "tts_name": "name", - "mailer_sid": "MDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "do_not_share_warning_enabled": false, - "custom_code_enabled": true, - "push": { - "include_date": true, - "notify_service_sid": null - }, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications", - "rate_limits": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits", - "messaging_configurations": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations", - "entities": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities", - "webhooks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "access_tokens": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AccessTokens" - } - } - ] - } - ''' - )) - - actual = self.client.verify.v2.services.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_record_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "name", - "code_length": 4, - "lookup_enabled": false, - "psd2_enabled": false, - "skip_sms_to_landlines": false, - "dtmf_input_required": false, - "tts_name": "name", - "mailer_sid": "MDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "do_not_share_warning_enabled": false, - "custom_code_enabled": true, - "push": { - "include_date": true, - "notify_service_sid": null - }, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "verification_checks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/VerificationCheck", - "verifications": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications", - "rate_limits": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/RateLimits", - "messaging_configurations": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/MessagingConfigurations", - "entities": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Entities", - "webhooks": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Webhooks", - "access_tokens": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AccessTokens" - } - } - ''' - )) - - actual = self.client.verify.v2.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/__init__.py b/tests/integration/video/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/video/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/video/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/video/v1/room/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/video/v1/room/room_participant/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 1d135dd2de..0000000000 --- a/tests/integration/video/v1/room/room_participant/test_room_participant_published_track.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding=utf-8 -r""" -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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks("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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks("MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .published_tracks.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/room/room_participant/test_room_participant_subscribe_rule.py b/tests/integration/video/v1/room/room_participant/test_room_participant_subscribe_rule.py deleted file mode 100644 index 4a350eee95..0000000000 --- a/tests/integration/video/v1/room/room_participant/test_room_participant_subscribe_rule.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding=utf-8 -r""" -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 SubscribeRulesTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribe_rules.fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SubscribeRules', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": null, - "date_updated": null, - "rules": [ - { - "type": "include", - "all": true, - "publisher": null, - "track": null, - "kind": null, - "priority": null - } - ] - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribe_rules.fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribe_rules.update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SubscribeRules', - )) - - def test_update_filters_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": null, - "date_updated": null, - "rules": [ - { - "type": "exclude", - "all": true, - "publisher": null, - "track": null, - "kind": null, - "priority": null - } - ] - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribe_rules.update() - - 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 dc7ce591ff..0000000000 --- a/tests/integration/video/v1/room/room_participant/test_room_participant_subscribed_track.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -r""" -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_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks("MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Participants/PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SubscribedTracks/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", - "publisher_sid": "PAbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "name": "bob-track", - "kind": "data", - "enabled": true, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribedTracks/MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks("MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .subscribed_tracks.list() - - 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 f19547acb1..0000000000 --- a/tests/integration/video/v1/room/test_recording.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -r""" -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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("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", - "date_updated": "2015-07-30T21:00:00Z", - "date_deleted": "2015-07-30T22:00:00Z", - "sid": "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "source_sid": "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 0, - "type": "audio", - "duration": 0, - "container_format": "mka", - "codec": "OPUS", - "track_name": "A name", - "offset": 10, - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://www.twilio.com", - "encryption_key": "public_key", - "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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("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("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", - "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", - "offset": 10, - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://www.twilio.com", - "encryption_key": "public_key", - "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?Status=completed&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&SourceSid=source_sid&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings?Status=completed&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&SourceSid=source_sid&PageSize=50&Page=0", - "next_page_url": null, - "key": "recordings" - } - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://video.twilio.com/v1/Rooms/RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings/RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .recordings("RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 a47d47d6d4..0000000000 --- a/tests/integration/video/v1/room/test_room_participant.py +++ /dev/null @@ -1,178 +0,0 @@ -# coding=utf-8 -r""" -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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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", - "subscribe_rules": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribeRules" - } - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("PAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.rooms("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("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", - "subscribe_rules": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribeRules" - } - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?Status=disconnected&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&Identity=alice&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants?Status=disconnected&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&Identity=alice&PageSize=50&Page=0", - "next_page_url": null, - "key": "participants" - } - } - ''' - )) - - actual = self.client.video.v1.rooms("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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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", - "subscribe_rules": "https://video.twilio.com/v1/Rooms/RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Participants/PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SubscribeRules" - } - } - ''' - )) - - actual = self.client.video.v1.rooms("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .participants("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 a32e980251..0000000000 --- a/tests/integration/video/v1/test_composition.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user*" - ], - "audio_sources_excluded": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "video_layout": { - "grid": { - "video_sources": [ - "*" - ], - "video_sources_excluded": [ - "MTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - }, - "pip": { - "video_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "video_sources_excluded": [], - "reuse": "none", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - } - }, - "resolution": "1280x720", - "format": "webm", - "bitrate": 64, - "size": 4, - "duration": 6, - "trim": true, - "media_external_location": null, - "encryption_key": null, - "url": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "media": "https://video.twilio.com/v1/Compositions/CJaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.compositions("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_enqueued_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "compositions": [], - "meta": { - "page": 0, - "page_size": 10, - "first_page_url": "https://video.twilio.com/v1/Compositions?Status=enqueued&PageSize=10&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Compositions?Status=enqueued&PageSize=10&Page=0", - "next_page_url": null, - "key": "compositions" - } - } - ''' - )) - - actual = self.client.video.v1.compositions.list() - - self.assertIsNotNone(actual) - - 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?Status=completed&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Compositions?Status=completed&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", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user*" - ], - "audio_sources_excluded": [], - "video_layout": { - "grid": { - "video_sources": [ - "user*" - ], - "video_sources_excluded": [], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - }, - "pip": { - "video_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - ], - "video_sources_excluded": [], - "reuse": "none", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - } - }, - "resolution": "1280x720", - "format": "webm", - "bitrate": 64, - "size": 4, - "duration": 6, - "trim": true, - "media_external_location": null, - "encryption_key": null, - "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?Status=completed&RoomSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Compositions?Status=completed&RoomSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&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("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("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(room_sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'RoomSid': "RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/Compositions', - data=values, - )) - - 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", - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "user*" - ], - "audio_sources_excluded": [ - "RTbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "video_layout": { - "custom": { - "video_sources": [ - "user*" - ], - "video_sources_excluded": [ - "RTcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 800, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [ - 2, - 3 - ] - } - }, - "trim": true, - "format": "mp4", - "resolution": "1920x1080", - "bitrate": 0, - "size": 0, - "duration": 0, - "media_external_location": null, - "encryption_key": null, - "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(room_sid="RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/test_composition_hook.py b/tests/integration/video/v1/test_composition_hook.py deleted file mode 100644 index 3f2875c831..0000000000 --- a/tests/integration/video/v1/test_composition_hook.py +++ /dev/null @@ -1,391 +0,0 @@ -# coding=utf-8 -r""" -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 CompositionHookTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/CompositionHooks/HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "My composition hook", - "enabled": true, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:01:33Z", - "sid": "HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "user*" - ], - "audio_sources_excluded": [ - "moderator*" - ], - "video_layout": { - "grid": { - "video_sources": [ - "*" - ], - "video_sources_excluded": [ - "moderator*" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - }, - "pip": { - "video_sources": [ - "student*" - ], - "video_sources_excluded": [], - "reuse": "none", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - } - }, - "resolution": "1280x720", - "format": "webm", - "trim": true, - "status_callback": "http://www.example.com", - "status_callback_method": "POST", - "url": "https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_hooks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/CompositionHooks', - )) - - def test_read_empty_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "composition_hooks": [], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/CompositionHooks?Enabled=True&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/CompositionHooks?Enabled=True&PageSize=50&Page=0", - "next_page_url": null, - "key": "composition_hooks" - } - } - ''' - )) - - actual = self.client.video.v1.composition_hooks.list() - - self.assertIsNotNone(actual) - - def test_read_results_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "composition_hooks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "My Special Hook1", - "enabled": true, - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:01:33Z", - "sid": "HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "*" - ], - "audio_sources_excluded": [], - "video_layout": { - "grid": { - "video_sources": [ - "*" - ], - "video_sources_excluded": [ - "moderator*" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - }, - "pip": { - "video_sources": [ - "student*" - ], - "video_sources_excluded": [], - "reuse": "none", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 0, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [] - } - }, - "resolution": "1280x720", - "format": "webm", - "trim": true, - "status_callback": "http://www.example.com", - "status_callback_method": "POST", - "url": "https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0", - "next_page_url": null, - "key": "composition_hooks" - } - } - ''' - )) - - actual = self.client.video.v1.composition_hooks.list() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://video.twilio.com/v1/CompositionHooks/HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_hooks.create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/CompositionHooks', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "friendly_name": "My composition hook", - "enabled": false, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": null, - "sid": "HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "user*", - "moderator" - ], - "audio_sources_excluded": [ - "admin" - ], - "video_layout": { - "custom": { - "video_sources": [ - "user*" - ], - "video_sources_excluded": [ - "moderator" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 800, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [ - 2, - 3 - ] - } - }, - "trim": true, - "format": "mp4", - "resolution": "1280x720", - "status_callback": "http://www.example.com", - "status_callback_method": "POST", - "url": "https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.composition_hooks.create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/CompositionHooks/HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_all_fields_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "friendly_name": "My composition hook", - "enabled": true, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "user*", - "moderator" - ], - "audio_sources_excluded": [ - "admin" - ], - "video_layout": { - "custom": { - "video_sources": [ - "user*" - ], - "video_sources_excluded": [ - "moderator" - ], - "reuse": "show_oldest", - "x_pos": 100, - "y_pos": 600, - "z_pos": 10, - "width": 800, - "height": 0, - "max_columns": 0, - "max_rows": 0, - "cells_excluded": [ - 2, - 3 - ] - } - }, - "trim": true, - "format": "mp4", - "resolution": "1280x720", - "status_callback": "http://www.example.com", - "status_callback_method": "POST", - "url": "https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) - - def test_update_with_defaults_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "friendly_name": "My composition hook", - "enabled": true, - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "sid": "HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "audio_sources": [ - "user*", - "moderator" - ], - "audio_sources_excluded": [ - "admin" - ], - "video_layout": {}, - "trim": true, - "format": "mp4", - "resolution": "1280x720", - "status_callback": null, - "status_callback_method": "POST", - "url": "https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.video.v1.composition_hooks("HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/test_composition_settings.py b/tests/integration/video/v1/test_composition_settings.py deleted file mode 100644 index 80337fd3d9..0000000000 --- a/tests/integration/video/v1/test_composition_settings.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding=utf-8 -r""" -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 CompositionSettingsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_settings().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/CompositionSettings/Default', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "string", - "aws_credentials_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "aws_s3_url": "https://www.twilio.com", - "aws_storage_enabled": true, - "encryption_enabled": true, - "url": "https://video.twilio.com/v1/CompositionSettings/Default" - } - ''' - )) - - actual = self.client.video.v1.composition_settings().fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.composition_settings().create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/CompositionSettings/Default', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "aws_credentials_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "aws_s3_url": "https://www.twilio.com", - "aws_storage_enabled": true, - "encryption_enabled": true, - "url": "https://video.twilio.com/v1/CompositionSettings/Default" - } - ''' - )) - - actual = self.client.video.v1.composition_settings().create(friendly_name="friendly_name") - - 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 897b9473e0..0000000000 --- a/tests/integration/video/v1/test_recording.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "offset": 10, - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://www.twilio.com", - "encryption_key": "public_key", - "links": { - "media": "https://video.twilio.com/v1/Recordings/RTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media" - } - } - ''' - )) - - actual = self.client.video.v1.recordings("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?Status=completed&SourceSid=source_sid&MediaType=audio&GroupingSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Recordings?Status=completed&SourceSid=source_sid&MediaType=audio&GroupingSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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", - "offset": 10, - "grouping_sids": { - "room_sid": "RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "participant_sid": "PAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "media_external_location": "https://www.twilio.com", - "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?Status=completed&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&SourceSid=source_sid&MediaType=audio&GroupingSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Recordings?Status=completed&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&SourceSid=source_sid&MediaType=audio&GroupingSid=RMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&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("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("RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/video/v1/test_recording_settings.py b/tests/integration/video/v1/test_recording_settings.py deleted file mode 100644 index 9d38c9aad0..0000000000 --- a/tests/integration/video/v1/test_recording_settings.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding=utf-8 -r""" -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 RecordingSettingsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.recording_settings().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://video.twilio.com/v1/RecordingSettings/Default', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "string", - "aws_credentials_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "aws_s3_url": "https://www.twilio.com", - "aws_storage_enabled": true, - "encryption_enabled": true, - "url": "https://video.twilio.com/v1/RecordingSettings/Default" - } - ''' - )) - - actual = self.client.video.v1.recording_settings().fetch() - - self.assertIsNotNone(actual) - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.video.v1.recording_settings().create(friendly_name="friendly_name") - - values = {'FriendlyName': "friendly_name", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://video.twilio.com/v1/RecordingSettings/Default', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "aws_credentials_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "encryption_key_sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "aws_s3_url": "https://www.twilio.com", - "aws_storage_enabled": true, - "encryption_enabled": true, - "url": "https://video.twilio.com/v1/RecordingSettings/Default" - } - ''' - )) - - actual = self.client.video.v1.recording_settings().create(friendly_name="friendly_name") - - self.assertIsNotNone(actual) diff --git a/tests/integration/video/v1/test_room.py b/tests/integration/video/v1/test_room.py deleted file mode 100644 index 99524dd20a..0000000000 --- a/tests/integration/video/v1/test_room.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -r""" -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("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("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?Status=completed&PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://video.twilio.com/v1/Rooms?Status=completed&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("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("RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="in-progress") - - self.assertIsNotNone(actual) diff --git a/tests/integration/voice/__init__.py b/tests/integration/voice/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/voice/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/voice/v1/__init__.py b/tests/integration/voice/v1/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/voice/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/voice/v1/connection_policy/__init__.py b/tests/integration/voice/v1/connection_policy/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/voice/v1/connection_policy/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/voice/v1/connection_policy/test_connection_policy_target.py b/tests/integration/voice/v1/connection_policy/test_connection_policy_target.py deleted file mode 100644 index a9d6e01352..0000000000 --- a/tests/integration/voice/v1/connection_policy/test_connection_policy_target.py +++ /dev/null @@ -1,226 +0,0 @@ -# coding=utf-8 -r""" -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 ConnectionPolicyTargetTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets.create(target="https://example.com") - - values = {'Target': "https://example.com", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Targets', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "target": "sip:sip-box.com:1234", - "priority": 1, - "weight": 20, - "enabled": true, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:36Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets/NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets.create(target="https://example.com") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Targets/NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "target": "sip:sip-box.com:1234", - "priority": 1, - "weight": 20, - "enabled": true, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets/NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Targets', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets?PageSize=50&Page=0", - "next_page_url": null, - "key": "targets" - }, - "targets": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "target": "sip:sip-box.com:1234", - "priority": 1, - "weight": 20, - "enabled": true, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets/NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets.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://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets?PageSize=50&Page=0", - "next_page_url": null, - "key": "targets" - }, - "targets": [] - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Targets/NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "updated_name", - "target": "sip:sip-updated.com:4321", - "priority": 2, - "weight": 10, - "enabled": false, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets/NEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Targets/NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ - .targets("NEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/voice/v1/dialing_permissions/__init__.py b/tests/integration/voice/v1/dialing_permissions/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/voice/v1/dialing_permissions/country/__init__.py b/tests/integration/voice/v1/dialing_permissions/country/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/country/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - diff --git a/tests/integration/voice/v1/dialing_permissions/country/test_highrisk_special_prefix.py b/tests/integration/voice/v1/dialing_permissions/country/test_highrisk_special_prefix.py deleted file mode 100644 index e13d1e2d1b..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/country/test_highrisk_special_prefix.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -r""" -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 HighriskSpecialPrefixTestCase(IntegrationTestCase): - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .countries("US") \ - .highrisk_special_prefixes.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/DialingPermissions/Countries/US/HighRiskSpecialPrefixes', - )) - - def test_read_lv_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "content": [ - { - "prefix": "+37181" - }, - { - "prefix": "+3719000" - } - ], - "meta": { - "first_page_url": "https://voice.twilio.com/v1/DialingPermissions/Countries/LV/HighRiskSpecialPrefixes?PageSize=50&Page=0", - "key": "content", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/DialingPermissions/Countries/LV/HighRiskSpecialPrefixes?PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .countries("US") \ - .highrisk_special_prefixes.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/voice/v1/dialing_permissions/test_bulk_country_update.py b/tests/integration/voice/v1/dialing_permissions/test_bulk_country_update.py deleted file mode 100644 index 549a6be72c..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/test_bulk_country_update.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -r""" -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 BulkCountryUpdateTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .bulk_country_updates.create(update_request="update_request") - - values = {'UpdateRequest': "update_request", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/DialingPermissions/BulkCountryUpdates', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "update_count": 1, - "update_request": "accepted" - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .bulk_country_updates.create(update_request="update_request") - - self.assertIsNotNone(actual) diff --git a/tests/integration/voice/v1/dialing_permissions/test_country.py b/tests/integration/voice/v1/dialing_permissions/test_country.py deleted file mode 100644 index 0c35809bd8..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/test_country.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -r""" -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_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .countries("US").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/DialingPermissions/Countries/US', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "iso_code": "US", - "name": "United States/Canada", - "country_codes": [ - "+1" - ], - "continent": "NORTH_AMERICA", - "low_risk_numbers_enabled": false, - "high_risk_special_numbers_enabled": false, - "high_risk_tollfraud_numbers_enabled": false, - "url": "https://voice.twilio.com/v1/DialingPermissions/Countries/US", - "links": { - "highrisk_special_prefixes": "https://voice.twilio.com/v1/DialingPermissions/Countries/US/HighRiskSpecialPrefixes" - } - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .countries("US").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .countries.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/DialingPermissions/Countries', - )) - - def test_read_us_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "content": [ - { - "iso_code": "US", - "name": "United States/Canada", - "country_codes": [ - "+1" - ], - "continent": "NORTH_AMERICA", - "low_risk_numbers_enabled": false, - "high_risk_special_numbers_enabled": false, - "high_risk_tollfraud_numbers_enabled": false, - "url": "https://voice.twilio.com/v1/DialingPermissions/Countries/US", - "links": { - "highrisk_special_prefixes": "https://voice.twilio.com/v1/DialingPermissions/Countries/US/HighRiskSpecialPrefixes" - } - } - ], - "meta": { - "first_page_url": "https://voice.twilio.com/v1/DialingPermissions/Countries?IsoCode=US&PageSize=50&Page=0", - "key": "content", - "next_page_url": null, - "page": 0, - "page_size": 50, - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/DialingPermissions/Countries?IsoCode=US&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .countries.list() - - self.assertIsNotNone(actual) diff --git a/tests/integration/voice/v1/dialing_permissions/test_settings.py b/tests/integration/voice/v1/dialing_permissions/test_settings.py deleted file mode 100644 index 7654a5d7f4..0000000000 --- a/tests/integration/voice/v1/dialing_permissions/test_settings.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -r""" -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 SettingsTestCase(IntegrationTestCase): - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .settings().fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/Settings', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "dialing_permissions_inheritance": true, - "url": "https://voice.twilio.com/v1/Settings" - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .settings().fetch() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.dialing_permissions \ - .settings().update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/Settings', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "dialing_permissions_inheritance": true, - "url": "https://voice.twilio.com/v1/Settings" - } - ''' - )) - - actual = self.client.voice.v1.dialing_permissions \ - .settings().update() - - self.assertIsNotNone(actual) diff --git a/tests/integration/voice/v1/test_byoc_trunk.py b/tests/integration/voice/v1/test_byoc_trunk.py deleted file mode 100644 index 765572f0fe..0000000000 --- a/tests/integration/voice/v1/test_byoc_trunk.py +++ /dev/null @@ -1,228 +0,0 @@ -# coding=utf-8 -r""" -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 ByocTrunkTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.byoc_trunks.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ByocTrunks', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "voice_url": "https://byoc.example.com/twilio/app", - "voice_method": "POST", - "voice_fallback_method": "POST", - "voice_fallback_url": "https://byoc.example.com/twilio/fallback", - "status_callback_method": "POST", - "status_callback_url": "https://byoc.example.com/twilio/status_callback", - "cnam_lookup_enabled": false, - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "from_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:36Z", - "url": "https://voice.twilio.com/v1/ByocTrunks/BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.byoc_trunks.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ByocTrunks/BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "voice_url": "https://byoc.example.com/twilio/app", - "voice_method": "POST", - "voice_fallback_method": "POST", - "voice_fallback_url": "https://byoc.example.com/twilio/fallback", - "status_callback_method": "POST", - "status_callback_url": "https://byoc.example.com/twilio/status_callback", - "cnam_lookup_enabled": false, - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "from_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ByocTrunks/BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.byoc_trunks.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ByocTrunks', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://voice.twilio.com/v1/ByocTrunks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ByocTrunks?PageSize=50&Page=0", - "next_page_url": null, - "key": "byoc_trunks" - }, - "byoc_trunks": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "voice_url": "https://byoc.example.com/twilio/app", - "voice_method": "POST", - "voice_fallback_method": "POST", - "voice_fallback_url": "https://byoc.example.com/twilio/fallback", - "status_callback_method": "POST", - "status_callback_url": "https://byoc.example.com/twilio/status_callback", - "cnam_lookup_enabled": false, - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "from_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ByocTrunks/BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.voice.v1.byoc_trunks.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://voice.twilio.com/v1/ByocTrunks?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ByocTrunks?PageSize=50&Page=0", - "next_page_url": null, - "key": "byoc_trunks" - }, - "byoc_trunks": [] - } - ''' - )) - - actual = self.client.voice.v1.byoc_trunks.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ByocTrunks/BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "update_name", - "voice_url": "https://byoc.example.com/twilio_updated/app", - "voice_method": "GET", - "voice_fallback_method": "GET", - "voice_fallback_url": "https://byoc.example.com/twilio_updated/fallback", - "status_callback_method": "GET", - "status_callback_url": "https://byoc.example.com/twilio_updated/status_callback", - "cnam_lookup_enabled": true, - "connection_policy_sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "from_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ByocTrunks/BYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://voice.twilio.com/v1/ByocTrunks/BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.voice.v1.byoc_trunks("BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/voice/v1/test_connection_policy.py b/tests/integration/voice/v1/test_connection_policy.py deleted file mode 100644 index 1b9080c5d2..0000000000 --- a/tests/integration/voice/v1/test_connection_policy.py +++ /dev/null @@ -1,204 +0,0 @@ -# coding=utf-8 -r""" -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 ConnectionPolicyTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies.create() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ConnectionPolicies', - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:36Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "targets": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets" - } - } - ''' - )) - - actual = self.client.voice.v1.connection_policies.create() - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "targets": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets" - } - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/ConnectionPolicies', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://voice.twilio.com/v1/ConnectionPolicies?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ConnectionPolicies?PageSize=50&Page=0", - "next_page_url": null, - "key": "connection_policies" - }, - "connection_policies": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "targets": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets" - } - } - ] - } - ''' - )) - - actual = self.client.voice.v1.connection_policies.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://voice.twilio.com/v1/ConnectionPolicies?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/ConnectionPolicies?PageSize=50&Page=0", - "next_page_url": null, - "key": "connection_policies" - }, - "connection_policies": [] - } - ''' - )) - - actual = self.client.voice.v1.connection_policies.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "updated_name", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "links": { - "targets": "https://voice.twilio.com/v1/ConnectionPolicies/NYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Targets" - } - } - ''' - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://voice.twilio.com/v1/ConnectionPolicies/NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.voice.v1.connection_policies("NYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/voice/v1/test_dialing_permissions.py b/tests/integration/voice/v1/test_dialing_permissions.py deleted file mode 100644 index 44d3874558..0000000000 --- a/tests/integration/voice/v1/test_dialing_permissions.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -r""" -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 DialingPermissionsTestCase(IntegrationTestCase): - pass diff --git a/tests/integration/voice/v1/test_ip_record.py b/tests/integration/voice/v1/test_ip_record.py deleted file mode 100644 index 46f10e363c..0000000000 --- a/tests/integration/voice/v1/test_ip_record.py +++ /dev/null @@ -1,203 +0,0 @@ -# coding=utf-8 -r""" -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 IpRecordTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.ip_records.create(ip_address="ip_address") - - values = {'IpAddress': "ip_address", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/IpRecords', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "ip_address": "10.2.3.4", - "cidr_prefix_length": 30, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:36Z", - "url": "https://voice.twilio.com/v1/IpRecords/ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.ip_records.create(ip_address="ip_address") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/IpRecords/ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "ip_address": "10.2.3.4", - "cidr_prefix_length": 30, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/IpRecords/ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.ip_records.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/IpRecords', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://voice.twilio.com/v1/IpRecords?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/IpRecords?PageSize=50&Page=0", - "next_page_url": null, - "key": "ip_records" - }, - "ip_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "friendly_name", - "ip_address": "10.2.3.4", - "cidr_prefix_length": 30, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/IpRecords/ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.voice.v1.ip_records.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://voice.twilio.com/v1/IpRecords?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/IpRecords?PageSize=50&Page=0", - "next_page_url": null, - "key": "ip_records" - }, - "ip_records": [] - } - ''' - )) - - actual = self.client.voice.v1.ip_records.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/IpRecords/ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "friendly_name": "update_name", - "ip_address": "10.2.3.4", - "cidr_prefix_length": 30, - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/IpRecords/ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://voice.twilio.com/v1/IpRecords/ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.voice.v1.ip_records("ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/voice/v1/test_source_ip_mapping.py b/tests/integration/voice/v1/test_source_ip_mapping.py deleted file mode 100644 index ca657ed7b4..0000000000 --- a/tests/integration/voice/v1/test_source_ip_mapping.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding=utf-8 -r""" -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 SourceIpMappingTestCase(IntegrationTestCase): - - def test_create_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.source_ip_mappings.create(ip_record_sid="ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", sip_domain_sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = { - 'IpRecordSid': "ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - 'SipDomainSid': "SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", - } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/SourceIpMappings', - data=values, - )) - - def test_create_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "sid": "IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_record_sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sip_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:36Z", - "url": "https://voice.twilio.com/v1/SourceIpMappings/IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.source_ip_mappings.create(ip_record_sid="ILXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", sip_domain_sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_fetch_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/SourceIpMappings/IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_record_sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sip_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/SourceIpMappings/IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_list_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.source_ip_mappings.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://voice.twilio.com/v1/SourceIpMappings', - )) - - def test_read_full_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "meta": { - "page": 0, - "page_size": 50, - "first_page_url": "https://voice.twilio.com/v1/SourceIpMappings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/SourceIpMappings?PageSize=50&Page=0", - "next_page_url": null, - "key": "source_ip_mappings" - }, - "source_ip_mappings": [ - { - "sid": "IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_record_sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sip_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/SourceIpMappings/IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - ''' - )) - - actual = self.client.voice.v1.source_ip_mappings.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://voice.twilio.com/v1/SourceIpMappings?PageSize=50&Page=0", - "previous_page_url": null, - "url": "https://voice.twilio.com/v1/SourceIpMappings?PageSize=50&Page=0", - "next_page_url": null, - "key": "source_ip_mappings" - }, - "source_ip_mappings": [] - } - ''' - )) - - actual = self.client.voice.v1.source_ip_mappings.list() - - self.assertIsNotNone(actual) - - def test_update_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(sip_domain_sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - values = {'SipDomainSid': "SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", } - - self.holodeck.assert_has_request(Request( - 'post', - 'https://voice.twilio.com/v1/SourceIpMappings/IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - data=values, - )) - - def test_update_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "sid": "IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_record_sid": "ILaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sip_domain_sid": "SDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", - "date_created": "2020-03-18T23:31:36Z", - "date_updated": "2020-03-18T23:31:37Z", - "url": "https://voice.twilio.com/v1/SourceIpMappings/IBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(sip_domain_sid="SDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://voice.twilio.com/v1/SourceIpMappings/IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.voice.v1.source_ip_mappings("IBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/wireless/__init__.py b/tests/integration/wireless/__init__.py deleted file mode 100644 index c9fc143806..0000000000 --- a/tests/integration/wireless/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/wireless/v1/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 c9fc143806..0000000000 --- a/tests/integration/wireless/v1/sim/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# coding=utf-8 -r""" -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 0dcdb80826..0000000000 --- a/tests/integration/wireless/v1/sim/test_data_session.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding=utf-8 -r""" -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("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, - "imei": 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", - "imei": "014931000129700" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DataSessions?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&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?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims("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 cf9721f9b5..0000000000 --- a/tests/integration/wireless/v1/sim/test_usage_record.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding=utf-8 -r""" -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("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": { - "billing_units": "USD", - "billed": 0, - "total": 3, - "from_sim": 1, - "to_sim": 2, - "home": { - "billing_units": "USD", - "billed": 0, - "total": 3, - "from_sim": 1, - "to_sim": 2 - }, - "national_roaming": { - "billing_units": "USD", - "billed": 0, - "total": 0, - "from_sim": 0, - "to_sim": 0 - }, - "international_roaming": [] - }, - "data": { - "billing_units": "USD", - "billed": 0.35, - "total": 3494609, - "upload": 731560, - "download": 2763049, - "units": "bytes", - "home": { - "billing_units": "USD", - "billed": 0.35, - "total": 3494609, - "upload": 731560, - "download": 2763049, - "units": "bytes" - }, - "national_roaming": { - "billing_units": "USD", - "billed": 0, - "total": 0, - "upload": 0, - "download": 0, - "units": "bytes" - }, - "international_roaming": [] - }, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "period": { - "start": "2015-07-30T20:00:00Z", - "end": "2015-07-30T20:00:00Z" - } - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands": {}, - "data": {}, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "period": {} - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&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?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.sims("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 6354b9750f..0000000000 --- a/tests/integration/wireless/v1/test_command.py +++ /dev/null @@ -1,271 +0,0 @@ -# coding=utf-8 -r""" -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("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_fetch_command_sms_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", - "delivery_receipt_requested": true, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "sms", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch() - - self.assertIsNotNone(actual) - - def test_fetch_command_ip_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", - "delivery_receipt_requested": false, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "to_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "ip", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands("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?Status=queued&Direction=from_sim&Sim=sim&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?Status=queued&Direction=from_sim&Sim=sim&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", - "delivery_receipt_requested": true, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "sms", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Commands?Status=queued&Direction=from_sim&Sim=sim&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?Status=queued&Direction=from_sim&Sim=sim&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.commands.list() - - self.assertIsNotNone(actual) - - def test_read_ip_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "commands": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "not_confirmable", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "delivery_receipt_requested": true, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "to_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "ip", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/Commands?Status=queued&Direction=to_sim&Transport=ip&Sim=sim&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?Status=queued&Direction=to_sim&Transport=ip&Sim=sim&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_command_sms_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", - "delivery_receipt_requested": true, - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "direction": "from_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "sms", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands.create(command="command") - - self.assertIsNotNone(actual) - - def test_create_command_ip_response(self): - self.holodeck.mock(Response( - 201, - ''' - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "command": "command", - "command_mode": "binary", - "date_created": "2015-07-30T20:00:00Z", - "date_updated": "2015-07-30T20:00:00Z", - "delivery_receipt_requested": true, - "direction": "to_sim", - "sid": "DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "sim_sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "status": "queued", - "transport": "ip", - "url": "https://wireless.twilio.com/v1/Commands/DCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.commands.create(command="command") - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.commands("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://wireless.twilio.com/v1/Commands/DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.wireless.v1.commands("DCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(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 42ae15ea2c..0000000000 --- a/tests/integration/wireless/v1/test_rate_plan.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-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", - "usage_notification_method": "POST", - "usage_notification_url": "https://callback.com", - "data_limit_strategy": "block", - "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("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": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-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", - "usage_notification_method": "POST", - "usage_notification_url": "https://callback.com", - "data_limit_strategy": "block", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans("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_limit_strategy": "block", - "data_metering": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-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", - "usage_notification_method": "POST", - "usage_notification_url": "https://callback.com", - "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("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": "payg", - "date_created": "2019-07-30T20:00:00Z", - "date_updated": "2019-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", - "usage_notification_method": "POST", - "usage_notification_url": "https://callback.com", - "data_limit_strategy": "block", - "url": "https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ''' - )) - - actual = self.client.wireless.v1.rate_plans("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("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("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 cdab8d50ea..0000000000 --- a/tests/integration/wireless/v1/test_sim.py +++ /dev/null @@ -1,310 +0,0 @@ -# coding=utf-8 -r""" -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("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", - "reset_status": null, - "url": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "ip_address": "192.168.1.1" - } - ''' - )) - - actual = self.client.wireless.v1.sims("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?Status=new&Iccid=iccid&RatePlan=rate_plan&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?Status=new&Iccid=iccid&RatePlan=rate_plan&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", - "reset_status": "resetting", - "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?Status=new&Iccid=iccid&RatePlan=rate_plan&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?Status=new&Iccid=iccid&RatePlan=rate_plan&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("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", - "reset_status": null, - "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("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_move_to_subaccount_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "account_sid": "ACbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "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/WPbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "usage_records": "https://wireless.twilio.com/v1/Sims/DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UsageRecords" - }, - "rate_plan_sid": "WPbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "sid": "DEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "iccid": "iccid", - "e_id": "e_id", - "status": "new", - "reset_status": null, - "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("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_update_reset_connectivity_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": "active", - "reset_status": "resetting", - "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("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update() - - self.assertIsNotNone(actual) - - def test_delete_request(self): - self.holodeck.mock(Response(500, '')) - - with self.assertRaises(TwilioException): - self.client.wireless.v1.sims("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.holodeck.assert_has_request(Request( - 'delete', - 'https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', - )) - - def test_delete_response(self): - self.holodeck.mock(Response( - 204, - None, - )) - - actual = self.client.wireless.v1.sims("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete() - - self.assertTrue(actual) diff --git a/tests/integration/wireless/v1/test_usage_record.py b/tests/integration/wireless/v1/test_usage_record.py deleted file mode 100644 index 92ec4eb9a0..0000000000 --- a/tests/integration/wireless/v1/test_usage_record.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding=utf-8 -r""" -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.usage_records.list() - - self.holodeck.assert_has_request(Request( - 'get', - 'https://wireless.twilio.com/v1/UsageRecords', - )) - - def test_fetch_response(self): - self.holodeck.mock(Response( - 200, - ''' - { - "usage_records": [ - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands": { - "billing_units": "USD", - "billed": 0, - "total": 3, - "from_sim": 1, - "to_sim": 2, - "home": { - "billing_units": "USD", - "billed": 0, - "total": 3, - "from_sim": 1, - "to_sim": 2 - }, - "national_roaming": { - "billing_units": "USD", - "billed": 0, - "total": 0, - "from_sim": 0, - "to_sim": 0 - }, - "international_roaming": [] - }, - "data": { - "billing_units": "USD", - "billed": 0.35, - "total": 3494609, - "upload": 731560, - "download": 2763049, - "units": "bytes", - "home": { - "billing_units": "USD", - "billed": 0.35, - "total": 3494609, - "upload": 731560, - "download": 2763049, - "units": "bytes" - }, - "national_roaming": { - "billing_units": "USD", - "billed": 0, - "total": 0, - "upload": 0, - "download": 0, - "units": "bytes" - }, - "international_roaming": [] - }, - "period": { - "start": "2015-07-30T20:00:00Z", - "end": "2015-07-30T20:00:00Z" - } - }, - { - "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "commands": {}, - "data": {}, - "period": {} - } - ], - "meta": { - "first_page_url": "https://wireless.twilio.com/v1/UsageRecords?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&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/UsageRecords?Start=2015-07-30T20%3A00%3A00Z&End=2015-07-30T20%3A00%3A00Z&PageSize=50&Page=0" - } - } - ''' - )) - - actual = self.client.wireless.v1.usage_records.list() - - self.assertIsNotNone(actual) diff --git a/tests/requirements.txt b/tests/requirements.txt index f20b5dea95..679f8e13d0 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -1,11 +1,14 @@ -Sphinx==1.8.0 -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 index 96927e13fb..46164e1174 100644 --- a/tests/unit/base/test_deprecation.py +++ b/tests/unit/base/test_deprecation.py @@ -5,9 +5,7 @@ class DeprecatedMethodTest(unittest.TestCase): - def test_deprecation_decorator(self): - @deprecated_method def old_method(): return True @@ -19,13 +17,12 @@ def old_method(): self.assertTrue(len(caught_warnings)) self.assertEqual( str(caught_warnings[0].message), - 'Function method .old_method() is deprecated' + "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') + @deprecated_method("new_method") def old_method(): return True @@ -37,6 +34,6 @@ def 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()' + "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 index 3cb11e3bed..1f1f6395eb 100644 --- a/tests/unit/base/test_version.py +++ b/tests/unit/base/test_version.py @@ -5,50 +5,64 @@ class TestPage(Page): - def __init__(self, version, response, *_args, **_kwargs): - super(TestPage, self).__init__(version, response) - def get_instance(self, payload): return payload -class VersionTestCase(IntegrationTestCase): +class StreamTestCase(IntegrationTestCase): def setUp(self): - super(VersionTestCase, self).setUp() + super(StreamTestCase, self).setUp() - self.holodeck.mock(Response( - 200, - ''' + 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')) + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) - self.holodeck.mock(Response( - 200, - ''' + 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')) + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json?Page=1" + ), + ) - self.holodeck.mock(Response( - 200, - ''' + 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')) + """, + ), + 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) + 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)) @@ -64,3 +78,14 @@ 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 a61326bcf7..8484e57b17 100644 --- a/tests/unit/http/test_http_client.py +++ b/tests/unit/http/test_http_client.py @@ -1,24 +1,26 @@ # -*- coding: utf-8 -*- +import os import unittest +from collections import OrderedDict -from mock import patch, Mock +from mock import Mock, patch from requests import Session -from twilio.base.version import Version 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() @@ -30,124 +32,204 @@ 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.client.request("doesnt matter", "doesnt matter") - self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) - self.assertIsNotNone(self.client.last_request) - self.assertIsNotNone(self.client.last_response) + 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'} + 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, None) + "doesnt matter", "doesnt matter", None, None, None, None, 30 + ) - 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_request_where_method_timeout_equals_zero(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"} try: self.client.request( - 'doesnt matter', 'doesnt matter', None, None, None, None, 0, None) + "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.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']) + 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.assertEqual("testing-unicode: Ω≈ç√, 💩", response.content) def test_request_where_class_timeout_equals_zero(self): - self.request_mock.url = 'https://api.twilio.com/' - self.request_mock.headers = {'Host': 'other.twilio.com'} + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} self.client.timeout = 0 try: - self.client.request( - 'doesnt matter', 'doesnt matter') + 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.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, None) + "doesnt matter", "doesnt matter", None, None, None, None, 15 + ) - 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_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.client.request("doesnt-matter", "doesnt-matter") - self.assertIsNotNone(self.client.last_request) - self.assertIsNone(self.client.last_response) + self.assertIsNotNone(self.client._test_only_last_request) + self.assertIsNone(self.client._test_only_last_response) def test_request_behind_proxy(self): - proxies = { - 'http': 'http://proxy.twilio.com', - 'https': 'https://proxy.twilio.com', - } + 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.assertEqual(proxies, self.session_mock.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 = """{ + error_text = """{ "code": 20001, "message": "Bad request", "more_info": "https://www.twilio.com/docs/errors/20001", @@ -159,7 +241,7 @@ def test_exception_with_details(self): 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') + self.fail("should not happen") except TwilioRestException as err: self.assertEqual(400, err.status) self.assertEqual(20001, err.code) @@ -169,9 +251,8 @@ def test_exception_with_details(self): 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): @@ -179,41 +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(MyVersion, self).__init__(domain) - self.version = 'v1' + 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 87a6ad26ed..5fdd4cb9fc 100644 --- a/tests/unit/http/test_validation_client.py +++ b/tests/unit/http/test_validation_client.py @@ -14,120 +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') + @patch("twilio.http.validation_client") def test_validate_ssl_certificate_success(self, http_client): - http_client.request.return_value = Response(200, 'success') + http_client.request.return_value = Response(200, "success") self.client.validate_ssl_certificate(http_client) - @patch('twilio.http.validation_client') + @patch("twilio.http.validation_client") def test_validate_ssl_certificate_error(self, http_client): - http_client.request.return_value = Response(504, 'error') + 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 c4aa70f359..9623dc52ad 100644 --- a/tests/unit/rest/test_client.py +++ b/tests/unit/rest/test_client.py @@ -1,99 +1,142 @@ import unittest +import aiounittest -from twilio.rest import ( - Client, - 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") +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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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 245c5ae43a..2159d4c910 100644 --- a/tests/unit/test_request_validator.py +++ b/tests/unit/test_request_validator.py @@ -1,15 +1,18 @@ # -*- 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): + if not settings.configured: + settings.configure() + token = "12345" self.validator = RequestValidator(token) @@ -22,52 +25,71 @@ def setUp(self): "Caller": "+14158675309", } self.expected = "RSOYDt4T1cUTdK1PDd93/VVr8B8=" - self.body = "{\"property\": \"value\", \"boolean\": true}" - self.bodyHash = "0a1ff7634d9ab3b95db5c9a2dfe9416e41502b283a80c7cf19632632f96e6620" + self.body = '{"property": "value", "boolean": true}' + self.bodyHash = ( + "0a1ff7634d9ab3b95db5c9a2dfe9416e41502b283a80c7cf19632632f96e6620" + ) self.uriWithBody = self.uri + "&bodySHA256=" + self.bodyHash - - def test_compute_signature_bytecode(self): - expected = b(self.expected) - signature = self.validator.compute_signature(self.uri, - self.params, - utf=False) - assert_equal(signature, expected) + self.duplicate_expected = "IK+Dwps556ElfBT0I3Rgjkr1wJU=" def test_compute_signature(self): - expected = (self.expected) - signature = self.validator.compute_signature(self.uri, - self.params, - utf=True) - assert_equal(signature, expected) + expected = self.expected + signature = self.validator.compute_signature(self.uri, self.params) + assert signature == expected def test_compute_hash_unicode(self): - expected = u(self.bodyHash) + expected = self.bodyHash body_hash = self.validator.compute_hash(self.body) - assert_equal(expected, body_hash) + assert expected == body_hash + + def test_compute_signature_duplicate_multi_dict(self): + expected = self.duplicate_expected + params = MultiDict( + [ + ("Sid", "CA123"), + ("SidAccount", "AC123"), + ("Digits", "5678"), # Ensure keys are sorted. + ("Digits", "1234"), # Ensure values are sorted. + ("Digits", "1234"), # Ensure duplicates are removed. + ] + ) + signature = self.validator.compute_signature(self.uri, params) + assert signature == expected + + def test_compute_signature_duplicate_query_dict(self): + expected = self.duplicate_expected + params = QueryDict( + "Sid=CA123&SidAccount=AC123&Digits=5678&Digits=1234&Digits=1234", + encoding="utf-8", + ) + signature = self.validator.compute_signature(self.uri, params) + assert signature == expected def test_validation(self): - assert_true(self.validator.validate(self.uri, self.params, self.expected)) + assert self.validator.validate(self.uri, self.params, self.expected) def test_validation_removes_port_on_https(self): uri = self.uri.replace(".com", ".com:1234") - assert_true(self.validator.validate(uri, self.params, self.expected)) + 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_true(self.validator.validate(uri, self.params, expected)) + 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_true(self.validator.validate(self.uri, self.params, expected)) + 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_true(self.validator.validate(uri, self.params, expected)) + 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_true(is_valid) + 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 b589cf460e..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(12345) + 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 4e097de9f5..286b5ba770 100644 --- a/tests/unit/twiml/test_messaging_response.py +++ b/tests/unit/twiml/test_messaging_response.py @@ -1,133 +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') + with r.add_child("message", tag="global") as mod: + mod.add_child("bold", "Hello") - assert_equal( - self.strip(r), - 'Hello') + assert ( + self.strip(r) + == 'Hello' + ) def test_mixed(self): r = MessagingResponse() - r.append('before') - r.add_child('Child').append('content') - r.append('after') + r.append("before") + r.add_child("Child").append("content") + r.append("after") - assert_equal( - self.strip(r), - 'beforecontentafter' + assert ( + self.strip(r) + == 'beforecontentafter' ) 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_equal( - self.strip(r), - 'example.com' + assert ( + self.strip(r) + == 'example.com' ) class TestText(TwilioTest): def test_text(self): r = MessagingResponse() - r.append('No tags!') + r.append("No tags!") - assert_equal( - self.strip(r), - 'No tags!' + assert ( + self.strip(r) + == 'No tags!' ) def text_mixed(self): r = MessagingResponse() - r.append('before') - r.append(Body('Content')) - r.append('after') + r.append("before") + r.append(Body("Content")) + r.append("after") - assert_equal( - self.strip(r), - 'beforeContentafter' + assert ( + self.strip(r) + == 'beforeContentafter' ) diff --git a/tests/unit/twiml/test_voice_response.py b/tests/unit/twiml/test_voice_response.py index 7f7e478556..df10fc7d62 100644 --- a/tests/unit/twiml/test_voice_response.py +++ b/tests/unit/twiml/test_voice_response.py @@ -1,32 +1,22 @@ # -*- 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), - '' + assert ( + self.strip(r) + == '' 'twilio sms' ) @@ -34,625 +24,606 @@ def test_response_chain(self): with VoiceResponse() as r: r.hangup() r.leave() - r.sms( - 'twilio sms', - to='+11234567890', - from_='+10987654321' - ) - - assert_equal( - self.strip(r), - '' + r.sms("twilio sms", to="+11234567890", from_="+10987654321") + + 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), - '' + 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), - '' + assert ( + self.strip(r) == '' '' - 'Hello, World' + "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), - '' + 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), - '' + assert ( + self.strip(r) == '' '' - 'TestConferenceAttributes' + "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), - '' + assert ( + self.strip(r) == '' '' - 'TestConferenceMutedAttribute' + "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), - '' + 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), - '' + 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), - '' + 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), - '' + 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), - '' + 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!') + r.append("No tags!") - assert_equal( - self.strip(r), - 'No tags!' + assert ( + self.strip(r) + == 'No tags!' ) def text_mixed(self): r = VoiceResponse() - r.append('before') - r.say('Content') - r.append('after') + r.append("before") + r.say("Content") + r.append("after") - assert_equal( - self.strip(r), - 'beforeContentafter' + 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') + with r.add_child("alexa", omnipresent="true") as alexa: + alexa.add_child("purchase", "Kindle") - assert_equal( - self.strip(r), - '' - 'Kindle' + assert ( + self.strip(r) + == '' + "Kindle" ) diff --git a/tox.ini b/tox.ini index 772c099d75..7db6cfc6fc 100644 --- a/tox.ini +++ b/tox.ini @@ -1,9 +1,9 @@ [tox] -envlist = py27, py3{4,5,6,7,8}, 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 cf53f7a180..5ce3ed13d0 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,3 +1,2 @@ - -__version_info__ = ('6', '44', '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 fdf9903d8d..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,18 +8,26 @@ 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 dictionary|None details: Additional error details returned for the exception + :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', details=None): + 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 @@ -28,43 +35,48 @@ def __init__(self, status, uri, msg="", code=None, method='GET', details=None): 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 1ef8ba5acf..e0f4a0339d 100644 --- a/twilio/base/obsolete.py +++ b/twilio/base/obsolete.py @@ -3,8 +3,7 @@ class ObsoleteException(Exception): - """ Base class for warnings about obsolete features. """ - pass + """Base class for warnings about obsolete features.""" def obsolete_client(func): @@ -16,8 +15,7 @@ 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 @@ -30,13 +28,17 @@ def deprecated_method(new_func=None): """ 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 '' + 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): diff --git a/twilio/base/page.py b/twilio/base/page.py index 3183efb180..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(cls, 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 f70a5f5db5..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 @@ -40,7 +40,6 @@ def prefixed_collapsible_map(m, prefix): return {} def flatten_dict(d, result=None, prv_keys=None): - if result is None: result = {} @@ -51,17 +50,30 @@ def flatten_dict(d, result=None, prv_keys=None): 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 @@ -79,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 8efcbee8a3..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('/')) + 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): + 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,28 +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']) - details = error_payload.get('details') - code = error_payload.get('code', response.status_code) - return TwilioRestException(response.status_code, uri, message, code, method, details) + 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") - def fetch(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + return json.loads(response.text) + + def fetch( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: """ Fetch a resource instance. """ @@ -80,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. """ @@ -101,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. """ @@ -122,30 +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) - return response.status_code == 204 + 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, + ) - def read_limits(self, limit=None, page_size=None): + return self._parse_delete(method, uri, response) + + def read_limits( + self, limit: Optional[int] = None, page_size: Optional[int] = None + ) -> Dict[str, object]: """ Takes a limit on the max number of records to read and a max page_size and calculates the max number of pages to read. - :param 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. """ 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, + "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. """ @@ -160,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_limit: 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 @@ -179,13 +385,68 @@ def stream(self, page, limit=None, page_limit=None): return current_page += 1 - if page_limit and page_limit is not values.unset and page_limit < current_page: + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): return page = page.next_page() - def create(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + async def stream_async( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> AsyncIterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = await page.next_page_async() + + def _parse_create(self, method: str, uri: str, response: Response) -> Any: + """ + Parse create response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to create record") + + return json.loads(response.text) + + def create( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: """ Create a resource instance. """ @@ -199,8 +460,30 @@ def create(self, method, uri, params=None, data=None, headers=None, auth=None, t timeout=timeout, allow_redirects=allow_redirects, ) + return self._parse_create(method, uri, response) - 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) + 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 de40b70089..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, parse_qs -except ImportError: - # python 2 backward compatibility - # noinspection PyUnresolvedReferences - from urllib import urlencode - # noinspection PyUnresolvedReferences - from urlparse import urlparse, urljoin, urlunparse, parse_qs - -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 a83493dd16..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -1,13 +1,15 @@ +import os import logging +from typing import Dict, Optional, Tuple from requests import Request, Session, hooks from requests.adapters import HTTPAdapter -from twilio.compat import urlencode + from twilio.http import HttpClient from twilio.http.request import Request as TwilioRequest from twilio.http.response import Response -_logger = logging.getLogger('twilio.http_client') +_logger = logging.getLogger("twilio.http_client") class TwilioHttpClient(HttpClient): @@ -15,89 +17,103 @@ class TwilioHttpClient(HttpClient): General purpose HTTP Client for interacting with the Twilio API """ - def __init__(self, pool_connections=True, request_hooks=None, timeout=None, logger=_logger, proxy=None, - max_retries=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 bool pool_connections + :param pool_connections :param request_hooks - :param int timeout: Timeout for the requests. - Timeout should never be zero (0) or less. + :param timeout: Timeout for the requests. + Timeout should never be zero (0) or less :param logger - :param dict proxy: Http proxy for the requests session - :param int max_retries: Maximum number of retries each request should attempt + :param proxy: Http proxy for the requests session + :param max_retries: Maximum number of retries each request should attempt """ + super().__init__(logger, False, timeout) self.session = Session() if pool_connections else None if self.session and max_retries is not None: - self.session.mount('https://', HTTPAdapter(max_retries=max_retries)) - self.last_request = None - self.last_response = None - self.logger = logger + 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() - - if timeout is not None and timeout <= 0: - raise ValueError(timeout) - self.timeout = timeout - self.proxy = proxy - - def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None, - allow_redirects=False): + self.proxy = proxy if proxy else {} + + def request( + self, + method: str, + url: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: """ Make an HTTP Request with parameters provided. - :param 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 not None and timeout <= 0: + 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: - self.logger.info('{method} Request: {url}?{query}'.format(query=urlencode(params), **kwargs)) - self.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: - self.logger.info('{method} Request: {url}'.format(**kwargs)) - if data: - self.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() - if self.proxy: - session.proxies = self.proxy 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 if timeout is not None else self.timeout, + timeout=timeout, + **settings, ) - self.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, response.headers) + 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 0c9e2c4504..af5a3b1706 100644 --- a/twilio/http/response.py +++ b/twilio/http/response.py @@ -1,5 +1,13 @@ +from typing import Any, Optional + + class Response(object): - def __init__(self, status_code, text, headers=None): + def __init__( + self, + status_code: int, + text: str, + headers: Optional[Any] = None, + ): self.content = text self.headers = headers self.cached = False @@ -7,8 +15,8 @@ def __init__(self, status_code, text, headers=None): 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 78abe1cbbc..1a4a83f0a5 100644 --- a/twilio/http/validation_client.py +++ b/twilio/http/validation_client.py @@ -3,20 +3,29 @@ from requests import Request, Session from twilio.base.exceptions import TwilioRestException -from twilio.compat import urlparse +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. @@ -33,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 @@ -52,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, @@ -79,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, @@ -87,20 +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://api.twilio.com:8443') + 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://api.twilio.com:8443', 'Failed to validate SSL certificate') + 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 63b9292bcf..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,20 +67,17 @@ 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(cls, values, joiner): - if isinstance(values, string_types): + if isinstance(values, str): return values return joiner.join(sorted(values)) @@ -83,6 +87,6 @@ def _hash(cls, 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 7e57923f5a..f7a0db361c 100644 --- a/twilio/request_validator.py +++ b/twilio/request_validator.py @@ -2,9 +2,7 @@ import hmac from hashlib import sha1, sha256 -from six import PY3, string_types - -from twilio.compat import izip, urlparse, parse_qs +from urllib.parse import urlparse, parse_qs def compare(string1, string2): @@ -19,7 +17,7 @@ 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 @@ -36,7 +34,7 @@ def remove_port(uri): if not uri.port: return uri.geturl() - new_netloc = uri.netloc.split(':')[0] + new_netloc = uri.netloc.split(":")[0] new_uri = uri._replace(netloc=new_netloc) return new_uri.geturl() @@ -61,32 +59,44 @@ def add_port(uri): 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 params: - for k, v in sorted(params.items()): - s += k + v + 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() @@ -108,18 +118,20 @@ def validate(self, uri, params, signature): uri_with_port = add_port(parsed_uri) uri_without_port = remove_port(parsed_uri) - valid_signature = False # Default fail - valid_signature_with_port = False 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, string_types): + 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) + 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 9f2ad72604..823cbbfaa0 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -1,784 +1,742 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. """ -import os -import platform -from twilio import __version__ -from twilio.base.exceptions import TwilioException -from twilio.base.obsolete import obsolete_client -from twilio.compat import ( - urlparse, - urlunparse, -) -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, edge=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 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.edge = edge or environment.get('TWILIO_EDGE') - """ :type : str """ - self.region = region or environment.get('TWILIO_REGION') - """ :type : str """ - - if not self.username or not self.password: - raise TwilioException("Credentials are required to create a TwilioClient") - - self.auth = (self.username, self.password) - """ :type : tuple(str, str) """ - self.http_client = http_client or TwilioHttpClient() - """ :type : HttpClient """ - - # Domains - self._accounts = None - self._api = None - self._autopilot = None - self._chat = None - self._conversations = None - self._fax = None - self._flex_api = None - self._insights = None - self._ip_messaging = None - self._lookups = None - self._messaging = None - self._monitor = None - self._notify = None - self._numbers = None - self._preview = None - self._pricing = None - self._proxy = None - self._serverless = None - self._studio = None - self._sync = None - self._taskrouter = None - self._trunking = None - self._verify = None - self._video = None - self._voice = None - self._wireless = None - self._supersim = None - self._bulkexports = 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' - - uri = self.get_hostname(uri) - - return self.http_client.request( - method, - uri, - params=params, - data=data, - headers=headers, - auth=auth, - timeout=timeout, - allow_redirects=allow_redirects - ) - - def get_hostname(self, uri): - """ - Determines the proper hostname given edge and region preferences - via client configuration or uri. - - :param str uri: Fully qualified url - - :returns: The final uri used to make the request - :rtype: str - """ - 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]) + super().__init__( + username, + password, + account_sid, + region, + http_client, + environment, + edge, + user_agent_extensions, + credential_provider, ) - return urlunparse(parsed_url) - @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 autopilot(self): + def assistants(self) -> "Assistants": """ - Access the Autopilot Twilio Domain + Access the Assistants Twilio Domain - :returns: Autopilot Twilio Domain - :rtype: twilio.rest.autopilot.Autopilot + :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._autopilot is None: - from twilio.rest.autopilot import Autopilot - self._autopilot = Autopilot(self) - return self._autopilot + if self._bulkexports is None: + from twilio.rest.bulkexports import Bulkexports + + self._bulkexports = Bulkexports(self) + return self._bulkexports @property - def chat(self): + 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 conversations(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 - :rtype: twilio.rest.conversations.Conversations """ if self._conversations is None: from twilio.rest.conversations import Conversations + self._conversations = Conversations(self) return self._conversations @property - def fax(self): + def events(self) -> "Events": """ - Access the Fax Twilio Domain + Access the Events Twilio Domain - :returns: Fax Twilio Domain - :rtype: twilio.rest.fax.Fax + :returns: Events Twilio Domain """ - if self._fax is None: - from twilio.rest.fax import Fax - self._fax = Fax(self) - return self._fax + if self._events is None: + from twilio.rest.events import Events + + self._events = Events(self) + return self._events @property - def flex_api(self): + def flex_api(self) -> "FlexApi": """ Access the FlexApi Twilio Domain :returns: FlexApi Twilio Domain - :rtype: twilio.rest.flex_api.FlexApi """ if self._flex_api is None: from twilio.rest.flex_api import FlexApi + self._flex_api = FlexApi(self) return self._flex_api @property - def insights(self): + 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 - :rtype: twilio.rest.insights.Insights """ if self._insights is None: from twilio.rest.insights import Insights + self._insights = Insights(self) return self._insights @property - def ip_messaging(self): + def intelligence(self) -> "Intelligence": + """ + Access the Intelligence Twilio Domain + + :returns: Intelligence Twilio Domain + """ + if self._intelligence is None: + from twilio.rest.intelligence import Intelligence + + self._intelligence = Intelligence(self) + return self._intelligence + + @property + def ip_messaging(self) -> "IpMessaging": """ Access the IpMessaging Twilio Domain :returns: IpMessaging Twilio Domain - :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 messaging(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 - :rtype: twilio.rest.messaging.Messaging """ if self._messaging is None: from twilio.rest.messaging import Messaging + self._messaging = Messaging(self) return self._messaging @property - def monitor(self): + 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 numbers(self): + def numbers(self) -> "Numbers": """ Access the Numbers Twilio Domain :returns: Numbers Twilio Domain - :rtype: twilio.rest.numbers.Numbers """ if self._numbers is None: from twilio.rest.numbers import Numbers + self._numbers = Numbers(self) return self._numbers @property - def preview(self): + 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 serverless(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 - :rtype: twilio.rest.serverless.Serverless """ if self._serverless is None: from twilio.rest.serverless import Serverless + self._serverless = Serverless(self) return self._serverless @property - def studio(self): + def studio(self) -> "Studio": """ 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 sync(self): + 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 - :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 taskrouter(self): + 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 verify(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 - :rtype: twilio.rest.verify.Verify """ if self._verify is None: from twilio.rest.verify import Verify + self._verify = Verify(self) return self._verify @property - def video(self): + 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 voice(self): + def voice(self) -> "Voice": """ Access the Voice Twilio Domain :returns: Voice Twilio Domain - :rtype: twilio.rest.voice.Voice """ 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 supersim(self): - """ - Access the Supersim Twilio Domain - - :returns: Supersim Twilio Domain - :rtype: twilio.rest.supersim.Supersim - """ - if self._supersim is None: - from twilio.rest.supersim import Supersim - self._supersim = Supersim(self) - return self._supersim - - @property - def bulkexports(self): - """ - Access the Bulkexports Twilio Domain - - :returns: Bulkexports Twilio Domain - :rtype: twilio.rest.bulkexports.Bulkexports - """ - if self._bulkexports is None: - from twilio.rest.bulkexports import Bulkexports - self._bulkexports = Bulkexports(self) - return self._bulkexports - - @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 balance(self): - """ - :rtype: twilio.rest.api.v2010.account.balance.BalanceList - """ + def balance(self) -> "BalanceList": return self.api.account.balance @property - def calls(self): - """ - :rtype: twilio.rest.api.v2010.account.call.CallList - """ + 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 b982272efe..e2275aea44 100644 --- a/twilio/rest/accounts/__init__.py +++ b/twilio/rest/accounts/__init__.py @@ -1,53 +1,35 @@ -# coding=utf-8 -r""" -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 0891ca6646..6f5012d0fa 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -1,42 +1,83 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 e4ad6de947..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 = {} + super().__init__(version) - # Components - self._public_key = None - self._aws = None + self._uri = "/Credentials" - @property - def public_key(self): - """ - Access the public_key - - :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 b3112c162b..ba5335accd 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -1,394 +1,609 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": + """ + Update the AwsInstance - return AwsPage(self._version, response, self._solution) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get_page(self, target_url): + :returns: The updated AwsInstance """ - Retrieve a specific page of AwsInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + ) - :param str target_url: API-generated URL for the requested results page + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "AwsInstance": + """ + Asynchronous coroutine to update the AwsInstance - :returns: Page of AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsPage + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return AwsPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def create(self, credentials, friendly_name=values.unset, - account_sid=values.unset): + :returns: Machine friendly representation """ - Create the AwsInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode credentials: A string that contains the AWS access credentials in the format : - :param unicode friendly_name: A string to describe the resource - :param unicode account_sid: The Subaccount this Credential should be associated with. - :returns: The created AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance +class AwsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Credentials': credentials, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) + Initialize the AwsContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + super().__init__(version) - return AwsInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/AWS/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a AwsContext + Deletes the AwsInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + :returns: True if delete succeeds, False otherwise """ - return AwsContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a AwsContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + async def delete_async(self) -> bool: """ - return AwsContext(self._version, sid=sid, ) + Asynchronous coroutine that 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 await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> AwsInstance: """ - Initialize the AwsPage + Fetch 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: The fetched AwsInstance """ - super(AwsPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of AwsInstance + 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.accounts.v1.credential.aws.AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance - """ - return AwsInstance(self._version, payload, ) + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> AwsInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the AwsInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched AwsInstance """ - return '' + headers = values.of({}) -class AwsContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the AwsContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.accounts.v1.credential.aws.AwsContext - :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext + def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: """ - super(AwsContext, self).__init__(version) + Update the AwsInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/AWS/{sid}'.format(**self._solution) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def fetch(self): + :returns: The updated AwsInstance """ - Fetch the AwsInstance - :returns: The fetched AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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: A string to describe the resource + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :returns: The updated AwsInstance - :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=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" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def delete(self): + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - def __repr__(self): +class AwsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: + """ + Build an instance of AwsInstance + + :param payload: Payload response from the API + """ + return AwsInstance(self._version, payload) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + self._uri = "/Credentials/AWS" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Create the AwsInstance - @property - def _proxy(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 """ - 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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 string that you assigned to describe the 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[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 RFC 2822 date and time in GMT when the 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[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 RFC 2822 date and time in GMT when the resource was last 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 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance """ - Fetch the AwsInstance + response = self._version.domain.twilio.request("GET", target_url) + return AwsPage(self._version, response) - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - def update(self, friendly_name=values.unset): + :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: A string to describe the resource + def get(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext - :returns: The 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 7e61674be4..c2b4f9bbee 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -1,394 +1,613 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Update the PublicKeyInstance - return PublicKeyPage(self._version, response, self._solution) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def get_page(self, target_url): + :returns: The updated PublicKeyInstance """ - Retrieve a specific page of PublicKeyInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + ) - :param str target_url: API-generated URL for the requested results page + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Asynchronous coroutine to update the PublicKeyInstance - :returns: Page of PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyPage + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return PublicKeyPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def create(self, public_key, friendly_name=values.unset, - account_sid=values.unset): + :returns: Machine friendly representation """ - Create the PublicKeyInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode public_key: A URL encoded representation of the public key - :param unicode friendly_name: A string to describe the resource - :param unicode account_sid: The Subaccount this Credential should be associated with. - :returns: The created PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance +class PublicKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'PublicKey': public_key, - 'FriendlyName': friendly_name, - 'AccountSid': account_sid, - }) + Initialize the PublicKeyContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + super().__init__(version) - return PublicKeyInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a PublicKeyContext + Deletes the PublicKeyInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + :returns: True if delete succeeds, False otherwise """ - return PublicKeyContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a PublicKeyContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + async def delete_async(self) -> bool: """ - return PublicKeyContext(self._version, sid=sid, ) + Asynchronous coroutine that 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 await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> PublicKeyInstance: """ - Initialize the PublicKeyPage + Fetch 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: The fetched PublicKeyInstance """ - super(PublicKeyPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of PublicKeyInstance + 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.accounts.v1.credential.public_key.PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - """ - return PublicKeyInstance(self._version, payload, ) + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> PublicKeyInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the PublicKeyInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched PublicKeyInstance """ - return '' + headers = values.of({}) -class PublicKeyContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the PublicKeyContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyContext + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: """ - super(PublicKeyContext, self).__init__(version) + Update the PublicKeyInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/PublicKeys/{sid}'.format(**self._solution) + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - def fetch(self): + :returns: The updated PublicKeyInstance """ - Fetch the PublicKeyInstance - :returns: The fetched PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 string to describe the resource + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :returns: The updated PublicKeyInstance - :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=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" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def delete(self): + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - def __repr__(self): +class PublicKeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: + """ + Build an instance of PublicKeyInstance + + :param payload: Payload response from the API + """ + return PublicKeyInstance(self._version, payload) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + self._uri = "/Credentials/PublicKeys" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Create the PublicKeyInstance - @property - def _proxy(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 """ - 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: The unique string that identifies the 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: The SID of the Account that created the Credential that the PublicKey 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: The string that you assigned to describe the 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 RFC 2822 date and time in GMT when the 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 RFC 2822 date and time in GMT when the 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance """ - Fetch the PublicKeyInstance + response = self._version.domain.twilio.request("GET", target_url) + return PublicKeyPage(self._version, response) - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - def update(self, friendly_name=values.unset): + :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 string to describe the resource + def get(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext - :returns: The 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 68711290a3..08d5885cbd 100644 --- a/twilio/rest/api/__init__.py +++ b/twilio/rest/api/__init__.py @@ -1,229 +1,258 @@ -# coding=utf-8 -r""" -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 balance(self): - """ - :rtype: twilio.rest.api.v2010.account.balance.BalanceList - """ + def balance(self) -> BalanceList: + warn( + "balance is deprecated. Use account.balance instead.", + DeprecationWarning, + stacklevel=2, + ) return self.account.balance @property - def calls(self): - """ - :rtype: twilio.rest.api.v2010.account.call.CallList - """ + 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 de7d181ec4..2efb4ff3d0 100644 --- a/twilio/rest/api/v2010/__init__.py +++ b/twilio/rest/api/v2010/__init__.py @@ -1,231 +1,59 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 balance(self): - """ - :rtype: twilio.rest.api.v2010.account.balance.BalanceList - """ - return self.account.balance - - @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 deabf1999f..7c7e2c1069 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -1,21 +1,33 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -38,986 +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 the 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: The 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(method='POST', uri=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']) + :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.update_async( + friendly_name=friendly_name, + status=status, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + return self._proxy.addresses - return AccountPage(self._version, response, self._solution) + @property + def applications(self) -> ApplicationList: + """ + Access the applications + """ + return self._proxy.applications - def get_page(self, target_url): + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: """ - Retrieve a specific page of AccountInstance records from the API. - Request is executed immediately + Access the authorized_connect_apps + """ + return self._proxy.authorized_connect_apps - :param str target_url: API-generated URL for the requested results page + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + """ + Access the available_phone_numbers + """ + return self._proxy.available_phone_numbers - :returns: Page of AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountPage + @property + def balance(self) -> BalanceList: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Access the balance + """ + return self._proxy.balance - return AccountPage(self._version, response, self._solution) + @property + def calls(self) -> CallList: + """ + Access the calls + """ + return self._proxy.calls - def get(self, sid): + @property + def conferences(self) -> ConferenceList: """ - Constructs a AccountContext + Access the conferences + """ + return self._proxy.conferences - :param sid: Fetch by unique Account Sid + @property + def connect_apps(self) -> ConnectAppList: + """ + Access the connect_apps + """ + return self._proxy.connect_apps - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + """ + Access the incoming_phone_numbers """ - return AccountContext(self._version, sid=sid, ) + return self._proxy.incoming_phone_numbers - def __call__(self, sid): + @property + def keys(self) -> KeyList: """ - Constructs a AccountContext + Access the keys + """ + return self._proxy.keys - :param sid: Fetch by unique Account Sid + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - :returns: twilio.rest.api.v2010.account.AccountContext - :rtype: twilio.rest.api.v2010.account.AccountContext + @property + def new_keys(self) -> NewKeyList: + """ + Access the new_keys """ - return AccountContext(self._version, sid=sid, ) + return self._proxy.new_keys - def __repr__(self): + @property + def new_signing_keys(self) -> NewSigningKeyList: """ - Provide a friendly representation + Access the new_signing_keys + """ + return self._proxy.new_signing_keys - :returns: Machine friendly representation - :rtype: str + @property + def notifications(self) -> NotificationList: """ - return '' + Access the notifications + """ + return self._proxy.notifications + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + return self._proxy.outgoing_caller_ids -class AccountPage(Page): - """ """ + @property + def queues(self) -> QueueList: + """ + Access the queues + """ + return self._proxy.queues - def __init__(self, version, response, solution): + @property + def recordings(self) -> RecordingList: + """ + Access the recordings """ - Initialize the AccountPage + return self._proxy.recordings - :param Version version: Version that contains the resource - :param Response response: Response from the API + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes - :returns: twilio.rest.api.v2010.account.AccountPage - :rtype: twilio.rest.api.v2010.account.AccountPage + @property + def signing_keys(self) -> SigningKeyList: """ - super(AccountPage, self).__init__(version, response) + Access the signing_keys + """ + return self._proxy.signing_keys - # Path Solution - self._solution = solution + @property + def sip(self) -> SipList: + """ + Access the sip + """ + return self._proxy.sip - def get_instance(self, payload): + @property + def tokens(self) -> TokenList: """ - Build an instance of AccountInstance + 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 - :returns: twilio.rest.api.v2010.account.AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + @property + def usage(self) -> UsageList: """ - return AccountInstance(self._version, payload, ) + Access the usage + """ + return self._proxy.usage - def __repr__(self): + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests + """ + return self._proxy.validation_requests + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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._balance = 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): + 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 - :rtype: twilio.rest.api.v2010.account.AccountInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return AccountInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def update(self, friendly_name=values.unset, status=values.unset): + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: """ Update the AccountInstance - :param 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: The updated AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: :returns: The updated AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance """ - data = values.of({'FriendlyName': friendly_name, 'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AccountInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) @property - def addresses(self): + 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 balance(self): + def balance(self) -> BalanceList: """ Access the balance - - :returns: twilio.rest.api.v2010.account.balance.BalanceList - :rtype: twilio.rest.api.v2010.account.balance.BalanceList """ if self._balance is None: - self._balance = BalanceList(self._version, account_sid=self._solution['sid'], ) + self._balance = BalanceList( + self._version, + self._solution["sid"], + ) return self._balance @property - def calls(self): + def calls(self) -> CallList: """ Access the calls - - :returns: twilio.rest.api.v2010.account.call.CallList - :rtype: twilio.rest.api.v2010.account.call.CallList """ 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 - - :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.get('auth_token'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'owner_account_sid': payload.get('owner_account_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'subresource_uris': payload.get('subresource_uris'), - 'type': payload.get('type'), - 'uri': payload.get('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 - - @property - def auth_token(self): """ - :returns: The authorization token for this account - :rtype: unicode - """ - return self._properties['auth_token'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def date_created(self): - """ - :returns: The date this account was created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The date this account was last updated - :rtype: datetime - """ - return self._properties['date_updated'] +class AccountPage(Page): - @property - def friendly_name(self): - """ - :returns: A human readable description of this account - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: """ - return self._properties['friendly_name'] + Build an instance of AccountInstance - @property - def owner_account_sid(self): + :param payload: Payload response from the API """ - :returns: The unique 34 character id representing the parent of this account - :rtype: unicode - """ - return self._properties['owner_account_sid'] + return AccountInstance(self._version, payload) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def status(self): - """ - :returns: The status of this account - :rtype: AccountInstance.Status + :returns: Machine friendly representation """ - return self._properties['status'] + return "" - @property - def subresource_uris(self): - """ - :returns: Account Instance Subresources - :rtype: unicode - """ - return self._properties['subresource_uris'] - @property - def type(self): - """ - :returns: The type of this account - :rtype: AccountInstance.Type - """ - return self._properties['type'] - - @property - def uri(self): - """ - :returns: The URI for this resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] +class AccountList(ListResource): - def fetch(self): + def __init__(self, version: Version): """ - Fetch the AccountInstance + Initialize the AccountList - :returns: The fetched AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance - """ - return self._proxy.fetch() + :param version: Version that contains the resource - def update(self, friendly_name=values.unset, status=values.unset): """ - Update the AccountInstance + super().__init__(version) - :param unicode friendly_name: FriendlyName to update - :param AccountInstance.Status status: Status to update the Account with + self._uri = "/Accounts.json" - :returns: The updated AccountInstance - :rtype: twilio.rest.api.v2010.account.AccountInstance + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: """ - return self._proxy.update(friendly_name=friendly_name, status=status, ) + Create the AccountInstance - @property - def addresses(self): - """ - Access the addresses + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` - :returns: twilio.rest.api.v2010.account.address.AddressList - :rtype: twilio.rest.api.v2010.account.address.AddressList + :returns: The created AccountInstance """ - return self._proxy.addresses - @property - def applications(self): - """ - Access the applications + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList - """ - return self._proxy.applications + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def authorized_connect_apps(self): - """ - Access the authorized_connect_apps + headers["Accept"] = "application/json" - :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 + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def available_phone_numbers(self): - """ - Access the available_phone_numbers + return AccountInstance(self._version, payload) - :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: """ - return self._proxy.available_phone_numbers + Asynchronously create the AccountInstance - @property - def balance(self): - """ - Access the balance + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` - :returns: twilio.rest.api.v2010.account.balance.BalanceList - :rtype: twilio.rest.api.v2010.account.balance.BalanceList + :returns: The created AccountInstance """ - return self._proxy.balance - @property - def calls(self): - """ - Access the calls + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"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["Content-Type"] = "application/x-www-form-urlencoded" - @property - def conferences(self): - """ - Access the conferences + headers["Accept"] = "application/json" - :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 09992c8b1e..77fc702ccc 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -1,603 +1,913 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 + 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 SID of the Account that is responsible for the resource + :returns: AddressContext for this AddressInstance + """ + if self._context is None: + self._context = AddressContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.address.AddressList - :rtype: twilio.rest.api.v2010.account.address.AddressList + def delete(self) -> bool: """ - super(AddressList, self).__init__(version) + Deletes the AddressInstance - # 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): + :returns: True if delete succeeds, False otherwise """ - Create the AddressInstance - - :param unicode customer_name: The name to associate with the new address - :param unicode street: The number and street address of the new address - :param unicode city: The city of the new address - :param unicode region: The state or region of the new address - :param unicode postal_code: The postal code of the new address - :param unicode iso_country: The ISO country code of the new address - :param unicode friendly_name: A string to describe the new resource - :param bool emergency_enabled: Whether to enable emergency calling on the new address - :param bool auto_correct_address: Whether we should automatically correct the address + return self._proxy.delete() - :returns: The created AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance + async def delete_async(self) -> bool: """ - 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, - }) + Asynchronous coroutine that deletes the AddressInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, limit=None, page_size=None): + def fetch(self) -> "AddressInstance": """ - Streams AddressInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Fetch the AddressInstance - :param unicode customer_name: The `customer_name` of the Address resources to read - :param unicode friendly_name: The string that identifies the Address resources to read - :param unicode iso_country: The ISO country code of the Address resources to read - :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: The fetched AddressInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page( - customer_name=customer_name, - friendly_name=friendly_name, - iso_country=iso_country, - page_size=limits['page_size'], - ) + async def fetch_async(self) -> "AddressInstance": + """ + Asynchronous coroutine to fetch the AddressInstance - return self._version.stream(page, limits['limit']) - def list(self, customer_name=values.unset, friendly_name=values.unset, - iso_country=values.unset, limit=None, page_size=None): + :returns: The fetched AddressInstance """ - Lists AddressInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Update the AddressInstance - :param unicode customer_name: The `customer_name` of the Address resources to read - :param unicode friendly_name: The string that identifies the Address resources to read - :param unicode iso_country: The ISO country code of the Address resources to read - :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: 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.address.AddressInstance] + :returns: The updated AddressInstance """ - return list(self.stream( + return self._proxy.update( + friendly_name=friendly_name, customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + return await self._proxy.update_async( friendly_name=friendly_name, - iso_country=iso_country, - limit=limit, - page_size=page_size, - )) + 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, + ) - 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): + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ - Retrieve a single page of AddressInstance records from the API. - Request is executed immediately + Access the dependent_phone_numbers + """ + return self._proxy.dependent_phone_numbers - :param unicode customer_name: The `customer_name` of the Address resources to read - :param unicode friendly_name: The string that identifies the Address resources to read - :param unicode iso_country: The ISO country code of the Address resources to read - :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 AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :returns: Machine friendly representation """ - data = values.of({ - 'CustomerName': customer_name, - 'FriendlyName': friendly_name, - 'IsoCountry': iso_country, - '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(method='GET', uri=self._uri, params=data, ) - return AddressPage(self._version, response, self._solution) +class AddressContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, account_sid: str, sid: str): """ - Retrieve a specific page of AddressInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the AddressContext - :returns: Page of AddressInstance - :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{sid}.json".format( + **self._solution ) - return AddressPage(self._version, response, self._solution) + self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None - def get(self, sid): + def delete(self) -> bool: """ - Constructs a AddressContext + Deletes the AddressInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + :returns: True if delete succeeds, False otherwise """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - def __call__(self, sid): - """ - Constructs a AddressContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + async def delete_async(self) -> bool: """ - return AddressContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Asynchronous coroutine that deletes the AddressInstance - 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 AddressPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> AddressInstance: """ - Initialize the AddressPage + Fetch the AddressInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that is responsible for the resource - :returns: twilio.rest.api.v2010.account.address.AddressPage - :rtype: twilio.rest.api.v2010.account.address.AddressPage + :returns: The fetched AddressInstance """ - super(AddressPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of AddressInstance + 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.address.AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance - """ - return AddressInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> AddressInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the AddressInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched AddressInstance """ - return '' + headers = values.of({}) -class AddressContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, sid): - """ - Initialize the AddressContext + 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 SID of the Account that is responsible for this address - :param sid: The unique string that identifies the resource + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.api.v2010.account.address.AddressContext - :rtype: twilio.rest.api.v2010.account.address.AddressContext + 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: """ - 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) + Update the AddressInstance - # Dependents - self._dependent_phone_numbers = None + :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 delete(self): + :returns: The updated AddressInstance """ - Deletes the AddressInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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({}) - def fetch(self): - """ - Fetch the AddressInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: The fetched AddressInstance - :rtype: twilio.rest.api.v2010.account.address.AddressInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return AddressInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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): - """ - Update the AddressInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode customer_name: The name to associate with the address - :param unicode street: The number and street address of the address - :param unicode city: The city of the address - :param unicode region: The state or region of the address - :param unicode postal_code: The postal code of the address - :param bool emergency_enabled: Whether to enable emergency calling on the address - :param bool auto_correct_address: Whether we should automatically correct the address + 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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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.get('account_sid'), - 'city': payload.get('city'), - 'customer_name': payload.get('customer_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'iso_country': payload.get('iso_country'), - 'postal_code': payload.get('postal_code'), - 'region': payload.get('region'), - 'sid': payload.get('sid'), - 'street': payload.get('street'), - 'uri': payload.get('uri'), - 'emergency_enabled': payload.get('emergency_enabled'), - 'validated': payload.get('validated'), - 'verified': payload.get('verified'), - } - - # 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 SID of the Account that is responsible for the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def city(self): - """ - :returns: The city in which the address is located - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['city'] + return "" - @property - def customer_name(self): - """ - :returns: The name associated with the address - :rtype: unicode - """ - return self._properties['customer_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was 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 RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the AddressList - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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 code of the address - :rtype: unicode """ - return self._properties['iso_country'] + super().__init__(version) - @property - def postal_code(self): - """ - :returns: The postal code of the address - :rtype: unicode + # 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: """ - return self._properties['postal_code'] + Create the AddressInstance - @property - def region(self): - """ - :returns: The state or region of the address - :rtype: unicode - """ - return self._properties['region'] + :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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created AddressInstance """ - return self._properties['sid'] - @property - def street(self): - """ - :returns: The number and street address of the address - :rtype: unicode - """ - return self._properties['street'] + 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 uri(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 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 """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + + 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['uri'] + 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: Whether emergency calling has been enabled on this number - :rtype: bool + 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['emergency_enabled'] + 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 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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: Whether the address has been validated to comply with local regulation - :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['validated'] + 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 verified(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: Whether the address has been verified to comply with regulation - :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['verified'] + 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, + } + ) - 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 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 the AddressInstance + response = self._version.domain.twilio.request("GET", target_url) + return AddressPage(self._version, response, self._solution) - :returns: The 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: A string to describe the resource - :param unicode customer_name: The name to associate with the address - :param unicode street: The number and street address of the address - :param unicode city: The city of the address - :param unicode region: The state or region of the address - :param unicode postal_code: The postal code of the address - :param bool emergency_enabled: Whether to enable emergency calling on the address - :param bool auto_correct_address: Whether we should automatically correct the address + def get(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext - :returns: The 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 13293507ad..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,440 +1,374 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :param address_sid: The unique string that identifies the resource - - :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']) - - 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 - - :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 DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return DependentPhoneNumberPage(self._version, response, self._solution) +class DependentPhoneNumberInstance(InstanceResource): - def get_page(self, target_url): - """ - Retrieve a specific page of DependentPhoneNumberInstance records from the API. - Request is executed immediately + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - :param str target_url: API-generated URL for the requested results page + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - :returns: Page of DependentPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + """ + :ivar sid: The unique string that that we created to identify the DependentPhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database. Can be: `true` or `false`. Caller ID lookups can cost $0.01 each. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar address_requirements: + :ivar capabilities: The set of Boolean properties that indicates whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar api_version: The API version used to start a new TwiML session. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from the phone number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + address_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.address_requirements: Optional[ + "DependentPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.api_version: Optional[str] = payload.get("api_version") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.emergency_status: Optional[ + "DependentPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } - 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 SID of the Account that created the resource - :param address_sid: The unique string that identifies the resource - :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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'voice_url': payload.get('voice_url'), - 'voice_method': payload.get('voice_method'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'address_requirements': payload.get('address_requirements'), - 'capabilities': payload.get('capabilities'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'api_version': payload.get('api_version'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'trunk_sid': payload.get('trunk_sid'), - 'emergency_status': payload.get('emergency_status'), - 'emergency_address_sid': payload.get('emergency_address_sid'), - 'uri': payload.get('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): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentPhoneNumberInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 string that you assigned to describe the resource - :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 in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + return self._version.stream(page, limits["limit"]) - @property - def voice_url(self): - """ - :returns: The URL we call when the phone number receives a call - :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 HTTP method used with the voice_url - :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 HTTP method used with voice_fallback_url - :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 URL we call when an error occurs in TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_caller_id_lookup(self): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - :returns: Whether to lookup the caller's name - :rtype: bool - """ - 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 RFC 2822 date and time in GMT that the resource was 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: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + :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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: """ - 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): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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: """ - 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 HTTP method to use with sms_url - :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 URL we call when the phone number receives an incoming SMS message - :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: Whether the phone number requires an Address registered with Twilio - :rtype: DependentPhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: dict - """ - return self._properties['capabilities'] + headers["Accept"] = "application/json" - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :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 HTTP method we use to call status_callback - :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 used to start a new TwiML session - :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 SID of the application that handles SMS messages sent to the phone number - :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 SID of the application that handles calls to the phone number - :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 SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - return self._properties['trunk_sid'] + headers["Accept"] = "application/json" - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :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 configuration to use for emergency calling - :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 of the resource, relative to `https://api.twilio.com` - :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 0c9a0ddc3a..555ab72b4a 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -1,649 +1,984 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +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" + ) - def __init__(self, version, account_sid): - """ - Initialize the ApplicationList + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ApplicationContext] = None - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + @property + def _proxy(self) -> "ApplicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: twilio.rest.api.v2010.account.application.ApplicationList - :rtype: twilio.rest.api.v2010.account.application.ApplicationList + :returns: ApplicationContext for this ApplicationInstance """ - super(ApplicationList, self).__init__(version) + if self._context is None: + self._context = ApplicationContext( + 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}/Applications.json'.format(**self._solution) - - def create(self, 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, friendly_name=values.unset): + def delete(self) -> bool: """ - Create the ApplicationInstance + Deletes the ApplicationInstance - :param unicode api_version: The API version to use to start a new TwiML session - :param unicode voice_url: The URL to call when the phone number receives a call - :param unicode voice_method: The HTTP method to use with the voice_url - :param unicode voice_fallback_url: The URL to call when a TwiML error occurs - :param unicode voice_fallback_method: The HTTP method to use with voice_fallback_url - :param unicode status_callback: The URL to send status information to your application - :param unicode status_callback_method: The HTTP method to use to call status_callback - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode sms_url: The URL to call when the phone number receives an incoming SMS message - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_fallback_url: The URL to call when an error occurs while retrieving or executing the TwiML - :param unicode sms_fallback_method: The HTTP method to use with sms_fallback_url - :param unicode sms_status_callback: The URL to send status information to your application - :param unicode message_status_callback: The URL to send message status information to your application - :param unicode friendly_name: A string to describe the new resource - :returns: The created ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.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': 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ApplicationInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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: The string that identifies the Application resources to read - :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.application.ApplicationInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ApplicationInstance - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "ApplicationInstance": """ - Lists ApplicationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch the ApplicationInstance - :param unicode friendly_name: The string that identifies the Application resources to read - :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: The fetched ApplicationInstance """ - 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) -> "ApplicationInstance": """ - Retrieve a single page of ApplicationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ApplicationInstance - :param unicode friendly_name: The string that identifies the Application resources to read - :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: The fetched ApplicationInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> "ApplicationInstance": + """ + Update the ApplicationInstance - return ApplicationPage(self._version, response, self._solution) + :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`. - def get_page(self, target_url): + :returns: The updated ApplicationInstance """ - Retrieve a specific page of ApplicationInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :returns: The updated ApplicationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ApplicationPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ApplicationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.application.ApplicationContext - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext +class ApplicationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Initialize the ApplicationContext - 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 Application resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. """ - Constructs a ApplicationContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Applications/{sid}.json".format( + **self._solution + ) - :returns: twilio.rest.api.v2010.account.application.ApplicationContext - :rtype: twilio.rest.api.v2010.account.application.ApplicationContext + def delete(self) -> bool: """ - return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Deletes the ApplicationInstance - 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 ApplicationPage(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 ApplicationPage + Asynchronous coroutine that deletes the ApplicationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :returns: twilio.rest.api.v2010.account.application.ApplicationPage - :rtype: twilio.rest.api.v2010.account.application.ApplicationPage + :returns: True if delete succeeds, False otherwise """ - super(ApplicationPage, 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) -> ApplicationInstance: """ - Build an instance of ApplicationInstance + Fetch 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: The fetched ApplicationInstance """ - return ApplicationInstance(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 ApplicationContext(InstanceContext): - """ """ + return ApplicationInstance( + 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) -> ApplicationInstance: """ - Initialize the ApplicationContext + Asynchronous coroutine to fetch the ApplicationInstance - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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(method='DELETE', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + 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: """ - Fetch the ApplicationInstance + Update the ApplicationInstance - :returns: The fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ApplicationInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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): + 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 """ - Update the ApplicationInstance - :param unicode friendly_name: A string to describe the resource - :param unicode api_version: The API version to use to start a new TwiML session - :param unicode voice_url: The URL to call when the phone number receives a call - :param unicode voice_method: The HTTP method to use with the voice_url - :param unicode voice_fallback_url: The URL to call when a TwiML error occurs - :param unicode voice_fallback_method: The HTTP method to use with voice_fallback_url - :param unicode status_callback: The URL to send status information to your application - :param unicode status_callback_method: The HTTP method to use to call status_callback - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode sms_url: The URL to call when the phone number receives an incoming SMS message - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_fallback_url: The URL to call when an error occurs while retrieving or executing the TwiML - :param unicode sms_fallback_method: The HTTP method to use with sms_fallback_url - :param unicode sms_status_callback: The URL to send status information to your application - :param unicode message_status_callback: The URL to send message status information to your application + 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({}) - :returns: The 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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'message_status_callback': payload.get('message_status_callback'), - 'sid': payload.get('sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_status_callback': payload.get('sms_status_callback'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'uri': payload.get('uri'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('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): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['api_version'] + return "" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] +class ApplicationList(ListResource): - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + def __init__(self, version: Version, account_sid: str): """ - return self._properties['friendly_name'] + Initialize the ApplicationList - @property - def message_status_callback(self): - """ - :returns: The URL to send message status information to your application - :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: The unique string that identifies the resource - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode + # 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: """ - return self._properties['sms_fallback_method'] + Create the ApplicationInstance - @property - def sms_fallback_url(self): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + :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`. - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + :returns: The created ApplicationInstance """ - return self._properties['sms_method'] - @property - def sms_status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['sms_status_callback'] + 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_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def uri(self): + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronously create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: """ - return self._properties['uri'] + 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. - @property - def voice_caller_id_lookup(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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: Whether to lookup the caller's name - :rtype: bool + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: """ - return self._properties['voice_caller_id_lookup'] + 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. - @property - def voice_fallback_method(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 HTTP method used with voice_fallback_url - :rtype: unicode + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: """ - return self._properties['voice_fallback_method'] + 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 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]: """ - :returns: The URL we call when a TwiML error occurs - :rtype: unicode + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: """ - return self._properties['voice_fallback_url'] + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately - @property - def voice_method(self): + :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 """ - :returns: The HTTP method used with the voice_url - :rtype: unicode + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: """ - return self._properties['voice_method'] + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately - @property - def voice_url(self): + :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 """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ApplicationPage: """ - return self._properties['voice_url'] + Retrieve a specific page of ApplicationInstance 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 ApplicationInstance """ - Deletes the ApplicationInstance + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> ApplicationPage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of ApplicationInstance """ - Fetch the ApplicationInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response, self._solution) - :returns: The fetched ApplicationInstance - :rtype: twilio.rest.api.v2010.account.application.ApplicationInstance + def get(self, sid: str) -> ApplicationContext: """ - return self._proxy.fetch() + Constructs a ApplicationContext - 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): + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. """ - Update the ApplicationInstance + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - :param unicode friendly_name: A string to describe the resource - :param unicode api_version: The API version to use to start a new TwiML session - :param unicode voice_url: The URL to call when the phone number receives a call - :param unicode voice_method: The HTTP method to use with the voice_url - :param unicode voice_fallback_url: The URL to call when a TwiML error occurs - :param unicode voice_fallback_method: The HTTP method to use with voice_fallback_url - :param unicode status_callback: The URL to send status information to your application - :param unicode status_callback_method: The HTTP method to use to call status_callback - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode sms_url: The URL to call when the phone number receives an incoming SMS message - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_fallback_url: The URL to call when an error occurs while retrieving or executing the TwiML - :param unicode sms_fallback_method: The HTTP method to use with sms_fallback_url - :param unicode sms_status_callback: The URL to send status information to your application - :param unicode message_status_callback: The URL to send message status information to your application + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext - :returns: The 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 b3a445b42a..cceb694c10 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -1,395 +1,458 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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" + + """ + :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") - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid or self.connect_app_sid, + } + self._context: Optional[AuthorizedConnectAppContext] = None - :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList + @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']) - 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. + 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.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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AuthorizedConnectAppContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 SID of the Connect App to fetch + 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 SID of the Connect App to fetch - :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 SID of the Account that created the resource - :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 SID of the Account that created the resource to fetch - :param connect_app_sid: The SID of the Connect App to fetch + :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 the 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: The fetched AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'connect_app_company_name': payload.get('connect_app_company_name'), - 'connect_app_description': payload.get('connect_app_description'), - 'connect_app_friendly_name': payload.get('connect_app_friendly_name'), - 'connect_app_homepage_url': payload.get('connect_app_homepage_url'), - 'connect_app_sid': payload.get('connect_app_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'permissions': payload.get('permissions'), - 'uri': payload.get('uri'), - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'connect_app_sid': connect_app_sid or self._properties['connect_app_sid'], - } + 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. - @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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: AuthorizedConnectAppContext for this AuthorizedConnectAppInstance - :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext + :returns: list that will contain up to limit results """ - 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 SID of the Account that created the resource - :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 the 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: A detailed 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: The name of 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 the Connect App - :rtype: unicode - """ - return self._properties['connect_app_homepage_url'] + headers["Accept"] = "application/json" - @property - def connect_app_sid(self): - """ - :returns: The SID that we assigned to the Connect 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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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 the 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 of the resource, relative to `https://api.twilio.com` - :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 the AuthorizedConnectAppInstance + Constructs a AuthorizedConnectAppContext - :returns: The 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 adf2f791bb..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/__init__.py +++ /dev/null @@ -1,543 +0,0 @@ -# coding=utf-8 -r""" -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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 ISO country code of the country to fetch available phone number information about - - :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 ISO country code of the country to fetch available phone number information about - - :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 SID of the Account requesting the available phone number Country resource - :param country_code: The ISO country code of the country to fetch available phone number information about - - :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 the AvailablePhoneNumberCountryInstance - - :returns: The fetched AvailablePhoneNumberCountryInstance - :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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.get('country_code'), - 'country': payload.get('country'), - 'uri': payload.get('uri'), - 'beta': payload.get('beta'), - 'subresource_uris': payload.get('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-3166-1 country code of the country. - :rtype: unicode - """ - return self._properties['country_code'] - - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] - - @property - def uri(self): - """ - :returns: The URI of the Country resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] - - @property - def beta(self): - """ - :returns: Whether all phone numbers available in the country are new to the Twilio platform. - :rtype: bool - """ - return self._properties['beta'] - - @property - def subresource_uris(self): - """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] - - def fetch(self): - """ - Fetch the AvailablePhoneNumberCountryInstance - - :returns: The 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 9941d4a19a..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/local.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 169feb6de7..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/machine_to_machine.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 a24d33b9e5..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/mobile.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 3f197e0961..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/national.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 dbe55aef73..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/shared_cost.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 dfc3b866b5..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/toll_free.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 b4472b7886..0000000000 --- a/twilio/rest/api/v2010/account/available_phone_number/voip.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding=utf-8 -r""" -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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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']) - - 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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 of the phone numbers to read - :param unicode contains: The pattern on which to match phone numbers - :param bool sms_enabled: Whether the phone numbers can receive text messages - :param bool mms_enabled: Whether the phone numbers can receive MMS messages - :param bool voice_enabled: Whether the phone numbers can receive calls. - :param bool exclude_all_address_required: Whether to exclude phone numbers that require an Address - :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local address - :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign address - :param bool beta: Whether to read phone numbers new to the Twilio platform - :param unicode near_number: Given a phone number, find a geographically close number within distance miles. (US/Canada only) - :param unicode near_lat_long: Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) - :param unicode distance: The search radius, in miles, for a near_ query. (US/Canada only) - :param unicode in_postal_code: Limit results to a particular postal code. (US/Canada only) - :param unicode in_region: Limit results to a particular region. (US/Canada only) - :param unicode in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) - :param unicode in_lata: Limit results to a specific local access and transport area. (US/Canada only) - :param unicode in_locality: Limit results to a particular locality - :param bool fax_enabled: Whether the phone numbers can receive faxes - :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 - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 account_sid - :param country_code: The ISO-3166-1 country code of the country. - - :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.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'lata': payload.get('lata'), - 'locality': payload.get('locality'), - 'rate_center': payload.get('rate_center'), - 'latitude': deserialize.decimal(payload.get('latitude')), - 'longitude': deserialize.decimal(payload.get('longitude')), - 'region': payload.get('region'), - 'postal_code': payload.get('postal_code'), - 'iso_country': payload.get('iso_country'), - 'address_requirements': payload.get('address_requirements'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'country_code': country_code, } - - @property - def friendly_name(self): - """ - :returns: A formatted version of the phone number - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def lata(self): - """ - :returns: The LATA of this phone number - :rtype: unicode - """ - return self._properties['lata'] - - @property - def locality(self): - """ - :returns: The locality or city of this phone number's location - :rtype: unicode - """ - return self._properties['locality'] - - @property - def rate_center(self): - """ - :returns: The rate center of this phone number - :rtype: unicode - """ - return self._properties['rate_center'] - - @property - def latitude(self): - """ - :returns: The latitude of this phone number's location - :rtype: unicode - """ - return self._properties['latitude'] - - @property - def longitude(self): - """ - :returns: The longitude of this phone number's location - :rtype: unicode - """ - return self._properties['longitude'] - - @property - def region(self): - """ - :returns: The two-letter state or province abbreviation of this phone number's location - :rtype: unicode - """ - return self._properties['region'] - - @property - def postal_code(self): - """ - :returns: The postal or ZIP code of this phone number's location - :rtype: unicode - """ - return self._properties['postal_code'] - - @property - def iso_country(self): - """ - :returns: The ISO country code of this phone number - :rtype: unicode - """ - return self._properties['iso_country'] - - @property - def address_requirements(self): - """ - :returns: The type of Address resource the phone number requires - :rtype: unicode - """ - return self._properties['address_requirements'] - - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] - - @property - def capabilities(self): - """ - :returns: Whether a phone number can receive calls or messages - :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 index 9c1c663a42..66bb91e9f9 100644 --- a/twilio/rest/api/v2010/account/balance.py +++ b/twilio/rest/api/v2010/account/balance.py @@ -1,149 +1,111 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page - - -class BalanceList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version, account_sid): - """ - Initialize the BalanceList - :param Version version: Version that contains the resource - :param account_sid: Account Sid. - - :returns: twilio.rest.api.v2010.account.balance.BalanceList - :rtype: twilio.rest.api.v2010.account.balance.BalanceList - """ - super(BalanceList, self).__init__(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 + """ - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Balance.json'.format(**self._solution) + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) - def fetch(self): - """ - Fetch the BalanceInstance + self.account_sid: Optional[str] = payload.get("account_sid") + self.balance: Optional[str] = payload.get("balance") + self.currency: Optional[str] = payload.get("currency") - :returns: The fetched BalanceInstance - :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return BalanceInstance(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 BalancePage(Page): - """ """ +class BalanceList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str): """ - Initialize the BalancePage + Initialize the BalanceList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: Account Sid. + :param version: Version that contains the resource + :param account_sid: The unique SID identifier of the Account. - :returns: twilio.rest.api.v2010.account.balance.BalancePage - :rtype: twilio.rest.api.v2010.account.balance.BalancePage """ - super(BalancePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Balance.json".format(**self._solution) - def get_instance(self, payload): + def fetch(self) -> BalanceInstance: """ - Build an instance of BalanceInstance - - :param dict payload: Payload response from the API + Asynchronously fetch the BalanceInstance - :returns: twilio.rest.api.v2010.account.balance.BalanceInstance - :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance - """ - return BalanceInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - def __repr__(self): + :returns: The fetched BalanceInstance """ - Provide a friendly representation + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) -class BalanceInstance(InstanceResource): - """ """ + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - def __init__(self, version, payload, account_sid): + async def fetch_async(self) -> BalanceInstance: """ - Initialize the BalanceInstance + Asynchronously fetch the BalanceInstance - :returns: twilio.rest.api.v2010.account.balance.BalanceInstance - :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance - """ - super(BalanceInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'balance': payload.get('balance'), - 'currency': payload.get('currency'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, } - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode + :returns: The fetched BalanceInstance """ - return self._properties['account_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def balance(self): - """ - :returns: Account balance - :rtype: unicode - """ - return self._properties['balance'] + headers["Accept"] = "application/json" - @property - def currency(self): - """ - :returns: Currency units - :rtype: unicode - """ - return self._properties['currency'] + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/api/v2010/account/call/__init__.py b/twilio/rest/api/v2010/account/call/__init__.py index fbcb2ed320..f7756c40ec 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -1,952 +1,1400 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class CallInstance(InstanceResource): - def __init__(self, version, account_sid): - """ - Initialize the CallList + class Status(object): + QUEUED = "queued" + RINGING = "ringing" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + BUSY = "busy" + FAILED = "failed" + NO_ANSWER = "no-answer" + CANCELED = "canceled" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created this resource + class UpdateStatus(object): + CANCELED = "canceled" + COMPLETED = "completed" - :returns: twilio.rest.api.v2010.account.call.CallList - :rtype: twilio.rest.api.v2010.account.call.CallList - """ - super(CallList, self).__init__(version) + """ + :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" + ) - # 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, - 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, - machine_detection_speech_threshold=values.unset, - machine_detection_speech_end_threshold=values.unset, - machine_detection_silence_timeout=values.unset, - async_amd=values.unset, async_amd_status_callback=values.unset, - async_amd_status_callback_method=values.unset, byoc=values.unset, - call_reason=values.unset, url=values.unset, twiml=values.unset, - application_sid=values.unset): + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None + + @property + def _proxy(self) -> "CallContext": """ - Create the CallInstance + 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, 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 fallback_url - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_event: The call progress events that we send to the `status_callback` URL. - :param unicode status_callback_method: HTTP Method to use with status_callback - :param unicode send_digits: The digits to dial after connecting to the number - :param unicode timeout: Number of seconds to wait for an answer - :param bool record: Whether to record the call - :param unicode recording_channels: The number of channels in the final recording - :param unicode recording_status_callback: The URL that we call when the recording is available to be accessed - :param unicode recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL - :param unicode sip_auth_username: The username used to authenticate the caller making a SIP call - :param unicode sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. - :param unicode machine_detection: Enable machine detection or end of greeting detection - :param unicode machine_detection_timeout: Number of seconds to wait for machine detection - :param unicode recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback` - :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 machine_detection_speech_threshold: Number of milliseconds for measuring stick for the length of the speech activity - :param unicode machine_detection_speech_end_threshold: Number of milliseconds of silence after speech activity - :param unicode machine_detection_silence_timeout: Number of milliseconds of initial silence - :param unicode async_amd: Enable asynchronous AMD - :param unicode async_amd_status_callback: The URL we should call to send amd status information to your application - :param unicode async_amd_status_callback_method: HTTP Method to use with async_amd_status_callback - :param unicode byoc: BYOC trunk SID (Beta) - :param unicode call_reason: Reason for the call (Branded Calls Beta) - :param unicode url: The absolute URL that returns TwiML for this call - :param unicode twiml: TwiML instructions for the call - :param unicode application_sid: The SID of the Application resource that will handle the call + :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: The created CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance - """ - data = values.of({ - 'To': to, - 'From': from_, - 'Url': url, - 'Twiml': twiml, - '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, - '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, - '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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return CallInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - 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): + def delete(self) -> bool: """ - 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. + Deletes the CallInstance - :param unicode to: Phone number or Client identifier of calls to include - :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: The status of the resources to read - :param datetime start_time_before: Only include calls that started on this date - :param datetime start_time: Only include calls that started on this date - :param datetime start_time_after: Only include calls that started on this date - :param datetime end_time_before: Only include calls that ended on this date - :param datetime end_time: Only include calls that ended on this date - :param datetime end_time_after: Only include calls that ended on this 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.call.CallInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - 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'], - ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CallInstance - return self._version.stream(page, limits['limit']) - 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): + :returns: True if delete succeeds, False otherwise """ - Lists CallInstance 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.delete_async() - :param unicode to: Phone number or Client identifier of calls to include - :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: The status of the resources to read - :param datetime start_time_before: Only include calls that started on this date - :param datetime start_time: Only include calls that started on this date - :param datetime start_time_after: Only include calls that started on this date - :param datetime end_time_before: Only include calls that ended on this date - :param datetime end_time: Only include calls that ended on this date - :param datetime end_time_after: Only include calls that ended on this 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) + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.CallInstance] + + :returns: The fetched CallInstance """ - 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 self._proxy.fetch() + + async def fetch_async(self) -> "CallInstance": """ - Retrieve a single page of CallInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the CallInstance - :param unicode to: Phone number or Client identifier of calls to include - :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: The status of the resources to read - :param datetime start_time_before: Only include calls that started on this date - :param datetime start_time: Only include calls that started on this date - :param datetime start_time_after: Only include calls that started on this date - :param datetime end_time_before: Only include calls that ended on this date - :param datetime end_time: Only include calls that ended on this date - :param datetime end_time_after: Only include calls that ended on this 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 CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallPage - """ - data = 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Update the CallInstance - return CallPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated CallInstance """ - Retrieve a specific page of CallInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallPage + :returns: The updated CallInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return CallPage(self._version, response, self._solution) + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events @property - def feedback_summaries(self): + def notifications(self) -> NotificationList: """ - Access the feedback_summaries + Access the notifications + """ + return self._proxy.notifications - :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList + @property + def payments(self) -> PaymentList: """ - if self._feedback_summaries is None: - self._feedback_summaries = FeedbackSummaryList( - self._version, - account_sid=self._solution['account_sid'], - ) - return self._feedback_summaries + Access the payments + """ + return self._proxy.payments - def get(self, sid): + @property + def recordings(self) -> RecordingList: """ - Constructs a CallContext + Access the recordings + """ + return self._proxy.recordings - :param sid: The SID of the Call resource to fetch + @property + def siprec(self) -> SiprecList: + """ + Access the siprec + """ + return self._proxy.siprec - :returns: twilio.rest.api.v2010.account.call.CallContext - :rtype: twilio.rest.api.v2010.account.call.CallContext + @property + def streams(self) -> StreamList: """ - return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Access the streams + """ + return self._proxy.streams - def __call__(self, sid): + @property + def transcriptions(self) -> TranscriptionList: """ - Constructs a CallContext + Access the transcriptions + """ + return self._proxy.transcriptions - :param sid: The SID of the Call resource 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 SID of the Account that created this resource + 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 SID of the Account that created the resource(s) to fetch - :param sid: The SID of the Call resource 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 - self._payments = 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(method='DELETE', uri=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 the CallInstance + Asynchronous coroutine to fetch the CallInstance + :returns: The fetched CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, - twiml=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: The absolute URL that returns TwiML for this call - :param unicode method: HTTP method to use to fetch TwiML - :param CallInstance.UpdateStatus status: The new 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 fallback_url - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: HTTP Method to use to call status_callback - :param unicode twiml: TwiML instructions for the call + :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 - :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, - 'Twiml': twiml, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return CallInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - @property - def recordings(self): + 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 """ - Access the recordings - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def events(self) -> EventList: """ - if self._recordings is None: - self._recordings = RecordingList( + Access the events + """ + 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): - """ - Access the feedback - - :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackList - """ - if self._feedback is None: - self._feedback = FeedbackList( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['sid'], - ) - return self._feedback - - @property - def payments(self): + def payments(self) -> PaymentList: """ Access the payments - - :returns: twilio.rest.api.v2010.account.call.payment.PaymentList - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentList """ 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._payments - 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 = { - 'sid': payload.get('sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'parent_call_sid': payload.get('parent_call_sid'), - 'account_sid': payload.get('account_sid'), - 'to': payload.get('to'), - 'to_formatted': payload.get('to_formatted'), - 'from_': payload.get('from'), - 'from_formatted': payload.get('from_formatted'), - 'phone_number_sid': payload.get('phone_number_sid'), - 'status': payload.get('status'), - 'start_time': deserialize.rfc2822_datetime(payload.get('start_time')), - 'end_time': deserialize.rfc2822_datetime(payload.get('end_time')), - 'duration': payload.get('duration'), - 'price': payload.get('price'), - 'price_unit': payload.get('price_unit'), - 'direction': payload.get('direction'), - 'answered_by': payload.get('answered_by'), - 'annotation': payload.get('annotation'), - 'api_version': payload.get('api_version'), - 'forwarded_from': payload.get('forwarded_from'), - 'group_sid': payload.get('group_sid'), - 'caller_name': payload.get('caller_name'), - 'queue_time': payload.get('queue_time'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'subresource_uris': payload.get('subresource_uris'), - } - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], } - @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 sid(self): + def siprec(self) -> SiprecList: """ - :returns: The unique string that identifies this resource - :rtype: unicode + Access the siprec """ - return self._properties['sid'] + if self._siprec is None: + self._siprec = SiprecList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._siprec @property - def date_created(self): + def streams(self) -> StreamList: """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + Access the streams """ - return self._properties['date_created'] + if self._streams is None: + self._streams = StreamList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._streams @property - def date_updated(self): + def transcriptions(self) -> TranscriptionList: """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime + Access the transcriptions """ - return self._properties['date_updated'] + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions @property - def parent_call_sid(self): + def user_defined_messages(self) -> UserDefinedMessageList: """ - :returns: The SID that identifies the call that created this leg. - :rtype: unicode + Access the user_defined_messages """ - return self._properties['parent_call_sid'] + 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 account_sid(self): + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: """ - :returns: The SID of the Account that created this resource - :rtype: unicode + Access the user_defined_message_subscriptions """ - return self._properties['account_sid'] + 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 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 + def __repr__(self) -> str: """ - return self._properties['to'] + Provide a friendly representation - @property - def to_formatted(self): - """ - :returns: The phone number, SIP address or Client identifier that received this call. Formatted for display. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['to_formatted'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def from_(self): - """ - :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_'] - @property - def from_formatted(self): - """ - :returns: The calling phone number, SIP address, or Client identifier formatted for display. - :rtype: unicode - """ - return self._properties['from_formatted'] +class CallPage(Page): - @property - def phone_number_sid(self): + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: """ - :returns: 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. - :rtype: unicode - """ - return self._properties['phone_number_sid'] + Build an instance of CallInstance - @property - def status(self): - """ - :returns: The status of this call. - :rtype: CallInstance.Status + :param payload: Payload response from the API """ - return self._properties['status'] + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def start_time(self): + def __repr__(self) -> str: """ - :returns: The start time of the call. Null if the call has not yet been dialed. - :rtype: datetime - """ - return self._properties['start_time'] + Provide a friendly representation - @property - def end_time(self): - """ - :returns: The end time of the call. Null if the call did not complete successfully. - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['end_time'] + return "" - @property - def duration(self): - """ - :returns: The length of the call in seconds. - :rtype: unicode - """ - return self._properties['duration'] - @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'] +class CallList(ListResource): - @property - def price_unit(self): - """ - :returns: The currency in which `Price` is measured. - :rtype: unicode + def __init__(self, version: Version, account_sid: str): """ - return self._properties['price_unit'] + Initialize the CallList - @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'] + :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 answered_by(self): - """ - :returns: Either `human` or `machine` if this call was initiated with answering machine detection. Empty otherwise. - :rtype: unicode """ - return self._properties['answered_by'] + super().__init__(version) - @property - def annotation(self): - """ - :returns: The annotation provided for the call - :rtype: unicode + # 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: """ - return self._properties['annotation'] + Create the CallInstance - @property - def api_version(self): - """ - :returns: The API Version used to create the call - :rtype: unicode - """ - return self._properties['api_version'] + :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. - @property - def forwarded_from(self): - """ - :returns: The forwarding phone number if this call was an incoming call forwarded from another number (depends on carrier supporting forwarding). Otherwise, empty. - :rtype: unicode + :returns: The created CallInstance """ - return self._properties['forwarded_from'] - @property - def group_sid(self): - """ - :returns: The Group SID associated with this call. If no Group is associated with the call, the field is empty. - :rtype: unicode - """ - return self._properties['group_sid'] + 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 caller_name(self): - """ - :returns: The caller's name if this call was an incoming call to a phone number with caller ID Lookup enabled. Otherwise, empty. - :rtype: unicode - """ - return self._properties['caller_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def queue_time(self): - """ - :returns: The wait time in milliseconds before the call is placed. - :rtype: unicode - """ - return self._properties['queue_time'] + headers["Accept"] = "application/json" - @property - def trunk_sid(self): - """ - :returns: The (optional) unique identifier of the trunk resource that was used for this call. - :rtype: unicode - """ - return self._properties['trunk_sid'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def uri(self): - """ - :returns: The URI of this resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def subresource_uris(self): + 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 """ - :returns: A list of related subresources identified by their relative URIs - :rtype: unicode + + 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['subresource_uris'] + 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. - def delete(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 """ - Deletes the CallInstance + 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"], + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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._proxy.delete() + 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 fetch(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]: """ - Fetch 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: The fetched CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + :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.fetch() + Retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - 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, - twiml=values.unset): + :returns: Page of CallInstance """ - Update the 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, + } + ) - :param unicode url: The absolute URL that returns TwiML for this call - :param unicode method: HTTP method to use to fetch TwiML - :param CallInstance.UpdateStatus status: The new 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 fallback_url - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: HTTP Method to use to call status_callback - :param unicode twiml: TwiML instructions for the call + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated CallInstance - :rtype: twilio.rest.api.v2010.account.call.CallInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallPage(self._version, response, self._solution) + + async def page_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallPage: + """ + Asynchronously retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallInstance """ - 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, + 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, + } ) - @property - def recordings(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 CallPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CallPage: """ - Access the recordings + 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 = self._version.domain.twilio.request("GET", target_url) + return CallPage(self._version, response, self._solution) - @property - def notifications(self): + async def get_page_async(self, target_url: str) -> CallPage: """ - Access the notifications + Asynchronously retrieve a specific page of CallInstance records from the API. + Request is executed immediately - :returns: twilio.rest.api.v2010.account.call.notification.NotificationList - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationList + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance """ - return self._proxy.notifications + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallPage(self._version, response, self._solution) - @property - def feedback(self): + def get(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 + ) - @property - def payments(self): + def __call__(self, sid: str) -> CallContext: """ - Access the payments + Constructs a CallContext - :returns: twilio.rest.api.v2010.account.call.payment.PaymentList - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentList + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update """ - return self._proxy.payments + 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 faa6c9e9f6..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback.py +++ /dev/null @@ -1,350 +0,0 @@ -# coding=utf-8 -r""" -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 unique sid that identifies this account - :param call_sid: The unique string that 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 unique sid that identifies this account - :param call_sid: The unique string that 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 unique sid that identifies this account - :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 the FeedbackInstance - - :param unicode quality_score: The call quality expressed as an integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: The 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(method='POST', uri=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 the FeedbackInstance - - :returns: The fetched FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: The call quality expressed as an integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: The 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(method='POST', uri=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.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'issues': payload.get('issues'), - 'quality_score': deserialize.integer(payload.get('quality_score')), - 'sid': payload.get('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 unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_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 issues(self): - """ - :returns: Issues experienced during the call - :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: A string that uniquely identifies this feedback resource - :rtype: unicode - """ - return self._properties['sid'] - - def create(self, quality_score, issue=values.unset): - """ - Create the FeedbackInstance - - :param unicode quality_score: The call quality expressed as an integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: The created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance - """ - return self._proxy.create(quality_score, issue=issue, ) - - def fetch(self): - """ - Fetch the FeedbackInstance - - :returns: The 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: The call quality expressed as an integer from 1 to 5 - :param FeedbackInstance.Issues issue: Issues experienced during the call - - :returns: The 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 59d47edd31..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback_summary.py +++ /dev/null @@ -1,386 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Account that created this resource - - :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 the FeedbackSummaryInstance - - :param date start_date: Only include feedback given on or after this date - :param date end_date: Only include feedback given on or before this date - :param bool include_subaccounts: `true` includes feedback from the specified account and its subaccounts - :param unicode status_callback: The URL that we will request when the feedback summary is complete - :param unicode status_callback_method: The HTTP method we use to make requests to the StatusCallback URL - - :returns: The 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(method='POST', uri=self._uri, data=data, ) - - return FeedbackSummaryInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - def get(self, sid): - """ - Constructs a FeedbackSummaryContext - - :param sid: A string that uniquely identifies this feedback summary resource - - :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: A string that uniquely identifies this feedback summary resource - - :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 SID of the Account that created this resource - - :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 unique sid that identifies this account - :param sid: A string that uniquely identifies this feedback summary resource - - :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 the FeedbackSummaryInstance - - :returns: The fetched FeedbackSummaryInstance - :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('account_sid'), - 'call_count': deserialize.integer(payload.get('call_count')), - 'call_feedback_count': deserialize.integer(payload.get('call_feedback_count')), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'end_date': deserialize.iso8601_datetime(payload.get('end_date')), - 'include_subaccounts': payload.get('include_subaccounts'), - 'issues': payload.get('issues'), - 'quality_score_average': deserialize.decimal(payload.get('quality_score_average')), - 'quality_score_median': deserialize.decimal(payload.get('quality_score_median')), - 'quality_score_standard_deviation': deserialize.decimal(payload.get('quality_score_standard_deviation')), - 'sid': payload.get('sid'), - 'start_date': deserialize.iso8601_datetime(payload.get('start_date')), - 'status': payload.get('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 unique sid that identifies this account - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def call_count(self): - """ - :returns: The total number of calls - :rtype: unicode - """ - return self._properties['call_count'] - - @property - def call_feedback_count(self): - """ - :returns: The total number of calls with a feedback entry - :rtype: unicode - """ - return self._properties['call_feedback_count'] - - @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 end_date(self): - """ - :returns: The latest feedback entry date in the summary - :rtype: datetime - """ - return self._properties['end_date'] - - @property - def include_subaccounts(self): - """ - :returns: Whether the feedback summary includes subaccounts - :rtype: bool - """ - return self._properties['include_subaccounts'] - - @property - def issues(self): - """ - :returns: Issues experienced during the call - :rtype: unicode - """ - return self._properties['issues'] - - @property - def quality_score_average(self): - """ - :returns: The average QualityScore of the feedback entries - :rtype: unicode - """ - return self._properties['quality_score_average'] - - @property - def quality_score_median(self): - """ - :returns: The median QualityScore of the feedback entries - :rtype: unicode - """ - return self._properties['quality_score_median'] - - @property - def quality_score_standard_deviation(self): - """ - :returns: The standard deviation of the quality scores - :rtype: unicode - """ - return self._properties['quality_score_standard_deviation'] - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this feedback entry - :rtype: unicode - """ - return self._properties['sid'] - - @property - def start_date(self): - """ - :returns: The earliest feedback entry date in the summary - :rtype: datetime - """ - return self._properties['start_date'] - - @property - def status(self): - """ - :returns: The status of the feedback summary - :rtype: FeedbackSummaryInstance.Status - """ - return self._properties['status'] - - def fetch(self): - """ - Fetch the FeedbackSummaryInstance - - :returns: The 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 d31a20ad68..fd9e8c0d00 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -1,503 +1,562 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :param call_sid: The SID of the Call the resource is associated with + 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) + 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, 'call_sid': call_sid, } - self._uri = '/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json'.format(**self._solution) + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context - def 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.call.notification.NotificationInstance] + :returns: The fetched NotificationInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - 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'], - ) + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance - return self._version.stream(page, limits['limit']) - 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): + :returns: The fetched NotificationInstance """ - Lists NotificationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param 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) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.call.notification.NotificationInstance] + def __repr__(self) -> str: """ - 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, - )) + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Retrieve a single page of NotificationInstance 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: 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: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationPage +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ - data = 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, - }) + Initialize the NotificationContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource to fetch. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + super().__init__(version) - return NotificationPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> NotificationInstance: """ - Retrieve a specific page of NotificationInstance records from the API. - Request is executed immediately + Fetch the NotificationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationPage + :returns: The fetched NotificationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return NotificationPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a NotificationContext + headers["Accept"] = "application/json" - :param sid: The unique string that identifies the resource + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.call.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationContext - """ - return NotificationContext( + 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 unique string that identifies the resource - :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 SID of the Account that created the resource - :param call_sid: The SID of the Call the resource is associated with - - :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 SID of the Account that created the resource to fetch - :param call_sid: The Call SID of the resource to fetch - :param sid: The unique string that identifies the 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 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) + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json".format( + **self._solution + ) + ) - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.call.notification.NotificationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + :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 __repr__(self): - """ - Provide a friendly representation + return self._version.stream(page, limits["limit"]) - :returns: Machine friendly representation - :rtype: str + 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]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) -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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'call_sid': payload.get('call_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'error_code': payload.get('error_code'), - 'log': payload.get('log'), - 'message_date': deserialize.rfc2822_datetime(payload.get('message_date')), - 'message_text': payload.get('message_text'), - 'more_info': payload.get('more_info'), - 'request_method': payload.get('request_method'), - 'request_url': payload.get('request_url'), - 'request_variables': payload.get('request_variables'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - # 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 SID of the Account that created the resource - :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 used to create the Call Notification resource - :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 SID of the Call the resource is associated with - :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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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): + def get_page(self, target_url: str) -> NotificationPage: """ - :returns: The HTTP body returned by your server - :rtype: unicode - """ - 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 + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance """ - return self._properties['response_headers'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def sid(self): + async def get_page_async(self, target_url: str) -> NotificationPage: """ - :returns: The unique string that identifies the 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['sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def uri(self): + def get(self, sid: str) -> NotificationContext: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. """ - return self._properties['uri'] + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> NotificationContext: """ - Fetch the NotificationInstance + Constructs a NotificationContext - :returns: The 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 __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 index 8c79995375..0f91860987 100644 --- a/twilio/rest/api/v2010/account/call/payment.py +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -1,399 +1,503 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, 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 +from twilio.base.version import Version -class PaymentList(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 PaymentInstance(InstanceResource): - def __init__(self, version, account_sid, call_sid): - """ - Initialize the PaymentList + class BankAccountType(object): + CONSUMER_CHECKING = "consumer-checking" + CONSUMER_SAVINGS = "consumer-savings" + COMMERCIAL_CHECKING = "commercial-checking" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the Payments resource. - :param call_sid: The SID of the Call the resource is associated with. + 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" - :returns: twilio.rest.api.v2010.account.call.payment.PaymentList - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentList - """ - super(PaymentList, self).__init__(version) + class PaymentMethod(object): + CREDIT_CARD = "credit-card" + ACH_DEBIT = "ach-debit" - # 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, status_callback, - bank_account_type=values.unset, charge_amount=values.unset, - currency=values.unset, description=values.unset, input=values.unset, - min_postal_code_length=values.unset, parameter=values.unset, - payment_connector=values.unset, payment_method=values.unset, - postal_code=values.unset, security_code=values.unset, - timeout=values.unset, token_type=values.unset, - valid_card_types=values.unset): - """ - Create the PaymentInstance + 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") - :param unicode idempotency_key: A unique token for each payment session that should be provided to maintain idempotency of the session. - :param unicode status_callback: The URL we should call to send status of payment session. - :param PaymentInstance.BankAccountType bank_account_type: If Payment source is ACH, type of bank account. - :param unicode charge_amount: If this field is present and greater than `0.0` payment source will be charged. - :param unicode currency: Currency `charge_amount` is in. - :param unicode description: Decription of the charge. - :param unicode input: Kind of medium customer would enter payment source information in. - :param unicode min_postal_code_length: If postal code is expected, minimum length of the postal code. - :param dict parameter: Additonal data to be sent over to payment provider. - :param unicode payment_connector: Payment connector that you would like Twilio to use for processing payments. - :param PaymentInstance.PaymentMethod payment_method: Payment source type. - :param bool postal_code: Whether to expect postal code during payment source data gathering. - :param bool security_code: Whether to expect security code during payment source data gathering. - :param unicode timeout: The number of seconds that we should allow customer to enter payment information - :param PaymentInstance.TokenType token_type: If tokenization of payment source is desired, this represents type of token. - :param unicode valid_card_types: List of card types accepted with each card types separated by space. + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[PaymentContext] = None - :returns: The created PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance + @property + def _proxy(self) -> "PaymentContext": """ - 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': postal_code, - 'SecurityCode': security_code, - 'Timeout': timeout, - 'TokenType': token_type, - 'ValidCardTypes': valid_card_types, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - return PaymentInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) + :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 get(self, sid): + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": """ - Constructs a PaymentContext + Update the PaymentInstance - :param sid: The SID of Payments session + :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: twilio.rest.api.v2010.account.call.payment.PaymentContext - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentContext + :returns: The updated PaymentInstance """ - return PaymentContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return self._proxy.update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, ) - def __call__(self, 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": """ - Constructs a PaymentContext + Asynchronous coroutine to update the PaymentInstance - :param sid: The SID of Payments session + :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: twilio.rest.api.v2010.account.call.payment.PaymentContext - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentContext + :returns: The updated PaymentInstance """ - return PaymentContext( - self._version, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=sid, + return await self._proxy.update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, ) - 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 PaymentPage(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 PaymentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ - Initialize the PaymentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the Payments resource. - :param call_sid: The SID of the Call the resource is associated with. + Initialize the PaymentContext - :returns: twilio.rest.api.v2010.account.call.payment.PaymentPage - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentPage + :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(PaymentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: """ - Build an instance of PaymentInstance + Update the PaymentInstance - :param dict payload: Payload response from the API + :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: twilio.rest.api.v2010.account.call.payment.PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance + :returns: The updated PaymentInstance """ - return PaymentInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } ) + headers = values.of({}) - def __repr__(self): - """ - Provide a friendly representation + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) -class PaymentContext(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 PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, account_sid, call_sid, 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: """ - Initialize the PaymentContext + Asynchronous coroutine to update the PaymentInstance - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that will update the resource - :param call_sid: The SID of the call that will create the resource. - :param sid: The SID of Payments session + :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: twilio.rest.api.v2010.account.call.payment.PaymentContext - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentContext + :returns: The updated PaymentInstance """ - super(PaymentContext, 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}/Payments/{sid}.json'.format(**self._solution) - - def update(self, idempotency_key, status_callback, capture=values.unset, - status=values.unset): - """ - Update the PaymentInstance + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) - :param unicode idempotency_key: A unique token for each payment session that should be provided to maintain idempotency of the session. - :param unicode status_callback: The URL we should call to send status of payment session. - :param PaymentInstance.Capture capture: Specific payment source information to expect. - :param PaymentInstance.Status status: Instruction to complete or cancel the transaction. + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: The updated PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance - """ - data = values.of({ - 'IdempotencyKey': idempotency_key, - 'StatusCallback': status_callback, - 'Capture': capture, - 'Status': status, - }) + headers["Accept"] = "application/json" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + 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 """ - 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 PaymentInstance(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 PaymentMethod(object): - CREDIT_CARD = "credit-card" - ACH_DEBIT = "ach-debit" - - class BankAccountType(object): - CONSUMER_CHECKING = "consumer-checking" - CONSUMER_SAVINGS = "consumer-savings" - COMMERCIAL_CHECKING = "commercial-checking" - - class TokenType(object): - ONE_TIME = "one-time" - REUSABLE = "reusable" - - 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 Status(object): - COMPLETE = "complete" - CANCEL = "cancel" +class PaymentList(ListResource): - def __init__(self, version, payload, account_sid, call_sid, sid=None): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ - Initialize the PaymentInstance + 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. - :returns: twilio.rest.api.v2010.account.call.payment.PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance """ - super(PaymentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'call_sid': payload.get('call_sid'), - 'sid': payload.get('sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'uri': payload.get('uri'), - } + 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}/Payments.json".format( + **self._solution + ) - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the PaymentInstance - :returns: PaymentContext for this PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentContext - """ - 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 + :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` - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Payments resource. - :rtype: unicode + :returns: The created PaymentInstance """ - return self._properties['account_sid'] - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with. - :rtype: unicode - """ - return self._properties['call_sid'] + 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"}) - @property - def sid(self): - """ - :returns: The SID of the Payments resource. - :rtype: unicode - """ - return self._properties['sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the 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 uri(self): + 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 """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + + 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: """ - return self._properties['uri'] + Constructs a PaymentContext - def update(self, idempotency_key, status_callback, capture=values.unset, - status=values.unset): + :param sid: The SID of Payments session that needs to be updated. """ - Update the PaymentInstance + return PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) - :param unicode idempotency_key: A unique token for each payment session that should be provided to maintain idempotency of the session. - :param unicode status_callback: The URL we should call to send status of payment session. - :param PaymentInstance.Capture capture: Specific payment source information to expect. - :param PaymentInstance.Status status: Instruction to complete or cancel the transaction. + def __call__(self, sid: str) -> PaymentContext: + """ + Constructs a PaymentContext - :returns: The updated PaymentInstance - :rtype: twilio.rest.api.v2010.account.call.payment.PaymentInstance + :param sid: The SID of Payments session that needs to be updated. """ - return self._proxy.update(idempotency_key, status_callback, capture=capture, status=status, ) + return PaymentContext( + 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/recording.py b/twilio/rest/api/v2010/account/call/recording.py index 36a9e95ad4..5b93ec6c95 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -1,596 +1,822 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class RecordingInstance(InstanceResource): - def __init__(self, version, account_sid, call_sid): - """ - Initialize the RecordingList + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param call_sid: The SID of the Call the resource is associated with + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" - :returns: twilio.rest.api.v2010.account.call.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingList - """ - super(RecordingList, self).__init__(version) + """ + :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 create(self, recording_status_callback_event=values.unset, - recording_status_callback=values.unset, - recording_status_callback_method=values.unset, trim=values.unset, - recording_channels=values.unset): + @property + def _proxy(self) -> "RecordingContext": """ - Create the RecordingInstance - - :param unicode recording_status_callback_event: The recording status changes that should generate a callback - :param unicode recording_status_callback: The callback URL on each selected recording event - :param unicode recording_status_callback_method: The HTTP method we should use to call `recording_status_callback` - :param unicode trim: Whether to trim the silence in the recording - :param unicode recording_channels: The number of channels that the output recording will be configured with + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + :returns: RecordingContext for this 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, - }) + 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 - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete(self) -> bool: + """ + Deletes the RecordingInstance - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - ) - def stream(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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.call.recording.RecordingInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that 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']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, date_created_before=values.unset, date_created=values.unset, - date_created_after=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the RecordingInstance - :param date date_created_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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: The fetched RecordingInstance """ - 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 self._proxy.fetch() - 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): + async def fetch_async(self) -> "RecordingInstance": """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RecordingInstance - :param date date_created_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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 """ - data = 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 await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RecordingPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + Update the RecordingInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingPage + :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 unique string that identifies the resource + :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 unique string that identifies the resource +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 SID of the Account that created the resource - :param call_sid: The SID of the Call the resource is associated with - :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({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> RecordingInstance: """ - return '' - + Asynchronous coroutine to fetch the RecordingInstance -class RecordingContext(InstanceContext): - """ """ - def __init__(self, version, account_sid, call_sid, sid): + :returns: The fetched RecordingInstance """ - Initialize the RecordingContext - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param call_sid: The Call SID of the resource to fetch - :param sid: The unique string that identifies the resource + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.call.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingContext - """ - super(RecordingContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) - def update(self, status, pause_behavior=values.unset): + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ Update the RecordingInstance - :param RecordingInstance.Status status: The new status of the recording - :param unicode pause_behavior: Whether to record or not during the pause period. + :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 - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance """ - data = values.of({'Status': status, 'PauseBehavior': pause_behavior, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return RecordingInstance( self._version, payload, - account_sid=self._solution['account_sid'], - call_sid=self._solution['call_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - def fetch(self): + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - Fetch the RecordingInstance + Asynchronous coroutine to update the RecordingInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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"], + call_sid=self._solution["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 "" -class RecordingInstance(InstanceResource): - """ """ +class RecordingList(ListResource): - class Status(object): - IN_PROGRESS = "in-progress" - PAUSED = "paused" - STOPPED = "stopped" - PROCESSING = "processing" - COMPLETED = "completed" - ABSENT = "absent" + 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'call_sid': payload.get('call_sid'), - 'conference_sid': payload.get('conference_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'start_time': deserialize.rfc2822_datetime(payload.get('start_time')), - 'duration': payload.get('duration'), - 'sid': payload.get('sid'), - 'price': deserialize.decimal(payload.get('price')), - 'uri': payload.get('uri'), - 'encryption_details': payload.get('encryption_details'), - 'price_unit': payload.get('price_unit'), - 'status': payload.get('status'), - 'channels': deserialize.integer(payload.get('channels')), - 'source': payload.get('source'), - 'error_code': deserialize.integer(payload.get('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): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the RecordingInstance - :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 + :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. - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: The created RecordingInstance """ - return self._properties['account_sid'] - @property - def api_version(self): - """ - :returns: The API version used to make the recording - :rtype: unicode - """ - return self._properties['api_version'] + 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 call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode - """ - return self._properties['call_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def conference_sid(self): - """ - :returns: The Conference SID that identifies the conference associated with the recording - :rtype: unicode - """ - return self._properties['conference_sid'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) - @property - def start_time(self): - """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime - """ - return self._properties['start_time'] + 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. - @property - def duration(self): - """ - :returns: The length of the recording in seconds - :rtype: unicode + :returns: The created RecordingInstance """ - return self._properties['duration'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + 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 price(self): - """ - :returns: The one-time cost of creating the recording. - :rtype: unicode - """ - return self._properties['price'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + headers["Accept"] = "application/json" - @property - def encryption_details(self): - """ - :returns: How to decrypt the recording. - :rtype: dict + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: """ - return self._properties['encryption_details'] + 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 currency used in the price property. - :rtype: unicode + 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['price_unit'] + 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 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 of the recording - :rtype: RecordingInstance.Status + 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['status'] + 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 channels(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 number of channels in the final recording file - :rtype: unicode + 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['channels'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def source(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: How the recording was created - :rtype: RecordingInstance.Source + 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['source'] + 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 error_code(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: More information about why the recording is missing, if status is `absent`. - :rtype: unicode + 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 = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) - def update(self, status, pause_behavior=values.unset): + async def get_page_async(self, target_url: str) -> RecordingPage: """ - Update the RecordingInstance + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :param RecordingInstance.Status status: The new status of the recording - :param unicode pause_behavior: Whether to record or not during the pause period. + :param target_url: API-generated URL for the requested results page - :returns: The updated RecordingInstance - :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance + :returns: Page of RecordingInstance """ - return self._proxy.update(status, pause_behavior=pause_behavior, ) + 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 the RecordingInstance + Constructs a RecordingContext - :returns: The 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 89ecd67459..672d9d0fea 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -1,574 +1,791 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the ConferenceList +class ConferenceInstance(InstanceResource): - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created this resource + 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" - :returns: twilio.rest.api.v2010.account.conference.ConferenceList - :rtype: twilio.rest.api.v2010.account.conference.ConferenceList - """ - super(ConferenceList, self).__init__(version) + class Status(object): + INIT = "init" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/Conferences.json'.format(**self._solution) + class UpdateStatus(object): + COMPLETED = "completed" - 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): - """ - 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. + """ + :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" + ) - :param date date_created_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_before: The `YYYY-MM-DD` value of the resources to read - :param date date_updated: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_after: The `YYYY-MM-DD` value of the resources to read - :param unicode friendly_name: The string that identifies the Conference resources to read - :param ConferenceInstance.Status status: The status of the resources to read - :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) + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConferenceContext] = None - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.ConferenceInstance] + @property + def _proxy(self) -> "ConferenceContext": """ - limits = self._version.read_limits(limit, page_size) - - 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'], - ) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - return self._version.stream(page, limits['limit']) + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - def 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): + def fetch(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. + Fetch the ConferenceInstance - :param date date_created_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_before: The `YYYY-MM-DD` value of the resources to read - :param date date_updated: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_after: The `YYYY-MM-DD` value of the resources to read - :param unicode friendly_name: The string that identifies the Conference resources to read - :param ConferenceInstance.Status status: The status of the resources to read - :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 self._proxy.fetch() - 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): + async def fetch_async(self) -> "ConferenceInstance": """ - Retrieve a single page of ConferenceInstance records from the API. - Request is executed immediately - - :param date date_created_before: The `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_before: The `YYYY-MM-DD` value of the resources to read - :param date date_updated: The `YYYY-MM-DD` value of the resources to read - :param date date_updated_after: The `YYYY-MM-DD` value of the resources to read - :param unicode friendly_name: The string that identifies the Conference resources to read - :param ConferenceInstance.Status status: The status of the resources to read - :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 ConferenceInstance - :returns: Page of ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferencePage - """ - data = 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return ConferencePage(self._version, response, self._solution) + :returns: The fetched ConferenceInstance + """ + return await self._proxy.fetch_async() - def get_page(self, target_url): + 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 specific page of ConferenceInstance records from the API. - Request is executed immediately + 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 self._proxy.update( + status=status, + announce_url=announce_url, + announce_method=announce_method, ) - return ConferencePage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": """ - Constructs a ConferenceContext + Asynchronous coroutine to update the ConferenceInstance - :param sid: The unique string that identifies this resource + :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: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + :returns: The updated ConferenceInstance """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.update_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) - def __call__(self, sid): + @property + def participants(self) -> ParticipantList: """ - Constructs a ConferenceContext - - :param sid: The unique string that identifies this resource + Access the participants + """ + return self._proxy.participants - :returns: twilio.rest.api.v2010.account.conference.ConferenceContext - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + @property + def recordings(self) -> RecordingList: """ - return ConferenceContext(self._version, account_sid=self._solution['account_sid'], 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 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 SID of the Account that created this resource + 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 SID of the Account that created the resource(s) to fetch - :param sid: The unique string that identifies this resource - :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({}) - # Dependents - self._participants = None - self._recordings = None + headers["Accept"] = "application/json" - def fetch(self): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: """ - Fetch the ConferenceInstance + Update the ConferenceInstance - :returns: The fetched ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.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: The updated ConferenceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 new status of the resource - :param unicode announce_url: The URL we should call to announce something into the conference - :param unicode announce_method: he HTTP method used to call announce_url + :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: The updated ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance """ - data = values.of({'Status': status, 'AnnounceUrl': announce_url, 'AnnounceMethod': announce_method, }) - payload = self._version.update(method='POST', uri=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 @property - def recordings(self): + def recordings(self) -> RecordingList: """ Access the recordings - - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList """ if self._recordings is None: self._recordings = RecordingList( self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) return self._recordings - 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 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"] + ) - 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" + def __repr__(self) -> str: + """ + Provide a friendly representation - def __init__(self, version, payload, account_sid, sid=None): - """ - Initialize the ConferenceInstance - - :returns: twilio.rest.api.v2010.account.conference.ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance - """ - super(ConferenceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'api_version': payload.get('api_version'), - 'friendly_name': payload.get('friendly_name'), - 'region': payload.get('region'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'uri': payload.get('uri'), - 'subresource_uris': payload.get('subresource_uris'), - 'reason_conference_ended': payload.get('reason_conference_ended'), - 'call_sid_ending_conference': payload.get('call_sid_ending_conference'), - } + :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 ConferenceList(ListResource): - :returns: ConferenceContext for this ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceContext + def __init__(self, version: Version, account_sid: str): """ - if self._context is None: - self._context = ConferenceContext( - self._version, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the ConferenceList - @property - def account_sid(self): - """ - :returns: The SID of the Account that created this resource - :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 Conference resource(s) to read. - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime """ - return self._properties['date_created'] + super().__init__(version) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :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_updated'] + 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 api_version(self): - """ - :returns: The API version used to create this conference - :rtype: unicode - """ - return self._properties['api_version'] + :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 friendly_name(self): - """ - :returns: A string that you assigned to describe this conference room - :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( + 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 region(self): - """ - :returns: A string that represents the Twilio Region where the conference was mixed - :rtype: unicode - """ - return self._properties['region'] + 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 sid(self): - """ - :returns: The unique string that identifies this resource - :rtype: unicode - """ - return self._properties['sid'] + :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 status(self): - """ - :returns: The status of this conference - :rtype: ConferenceInstance.Status + :returns: Generator that will yield up to limit results """ - return self._properties['status'] + 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 uri(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 URI of this resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + 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 subresource_uris(self): - """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + :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, + ) + ) - @property - def reason_conference_ended(self): - """ - :returns: The reason why a conference ended. - :rtype: ConferenceInstance.ReasonConferenceEnded + 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: """ - return self._properties['reason_conference_ended'] + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately - @property - def call_sid_ending_conference(self): + :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 call SID that caused the conference to end - :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 = 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 """ - return self._properties['call_sid_ending_conference'] + 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"}) - def fetch(self): + 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: """ - Fetch the ConferenceInstance + Retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately - :returns: The fetched ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response, self._solution) - def update(self, status=values.unset, announce_url=values.unset, - announce_method=values.unset): + async def get_page_async(self, target_url: str) -> ConferencePage: """ - Update the ConferenceInstance + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately - :param ConferenceInstance.UpdateStatus status: The new status of the resource - :param unicode announce_url: The URL we should call to announce something into the conference - :param unicode announce_method: he HTTP method used to call announce_url + :param target_url: API-generated URL for the requested results page - :returns: The updated ConferenceInstance - :rtype: twilio.rest.api.v2010.account.conference.ConferenceInstance + :returns: Page of ConferenceInstance """ - return self._proxy.update(status=status, announce_url=announce_url, announce_method=announce_method, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response, self._solution) - @property - def participants(self): + def get(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 + ) - @property - def recordings(self): + def __call__(self, sid: str) -> ConferenceContext: """ - Access the recordings + Constructs a ConferenceContext - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update """ - return self._proxy.recordings + 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 f1f22bef31..3c49e5387c 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -1,698 +1,1201 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + + class Status(object): + QUEUED = "queued" + CONNECTING = "connecting" + RINGING = "ringing" + CONNECTED = "connected" + COMPLETE = "complete" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Participant resource is associated with. + :ivar label: The user-specified label of this participant, if one was given when the participant was created. This may be used to fetch, update or delete the participant. + :ivar call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :ivar coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :ivar conference_sid: The SID of the conference the participant is in. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar end_conference_on_exit: Whether the conference ends when the participant leaves. Can be: `true` or `false` and the default is `false`. If `true`, the conference ends and all other participants drop out when the participant leaves. + :ivar muted: Whether the participant is muted. Can be `true` or `false`. + :ivar hold: Whether the participant is on hold. Can be `true` or `false`. + :ivar start_conference_on_enter: Whether the conference starts when the participant joins the conference, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :ivar status: + :ivar queue_time: The wait time in milliseconds before participant's call is placed. Only available in the response to a create participant request. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + call_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.label: Optional[str] = payload.get("label") + self.call_sid_to_coach: Optional[str] = payload.get("call_sid_to_coach") + self.coaching: Optional[bool] = payload.get("coaching") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.end_conference_on_exit: Optional[bool] = payload.get( + "end_conference_on_exit" + ) + self.muted: Optional[bool] = payload.get("muted") + self.hold: Optional[bool] = payload.get("hold") + self.start_conference_on_enter: Optional[bool] = payload.get( + "start_conference_on_enter" + ) + self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.queue_time: Optional[str] = payload.get("queue_time") + self.uri: Optional[str] = payload.get("uri") - def __init__(self, version, account_sid, conference_sid): + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": """ - 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 account_sid: The SID of the Account that created the resource - :param conference_sid: The SID of the conference the participant is in + :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 - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList + def delete(self) -> bool: """ - super(ParticipantList, self).__init__(version) + Deletes the ParticipantInstance - # 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, label=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, - coaching=values.unset, call_sid_to_coach=values.unset, - jitter_buffer_size=values.unset, byoc=values.unset, - caller_id=values.unset): + + :returns: True if delete succeeds, False otherwise """ - Create the ParticipantInstance + return self._proxy.delete() - :param unicode from_: The phone number, Client identifier, or username portion of SIP address that made this call. - :param unicode to: The phone number, SIP address or Client identifier that received this call. - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call `status_callback` - :param unicode status_callback_event: Set state change events that will trigger a callback - :param unicode label: The label of this participant - :param unicode timeout: he number of seconds that we should wait for an answer - :param bool record: Whether to record the participant and their conferences - :param bool muted: Whether to mute the agent - :param unicode beep: Whether to play a notification beep to the conference when the participant joins - :param bool start_conference_on_enter: Whether the conference starts when the participant joins the conference - :param bool end_conference_on_exit: Whether to end the conference when the participant leaves - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool early_media: Whether agents can hear the state of the outbound call - :param unicode max_participants: The maximum number of agent conference participants - :param unicode conference_record: Whether to record the conference the participant is joining - :param unicode conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files - :param unicode conference_status_callback: The callback URL for conference events - :param unicode conference_status_callback_method: HTTP method for requesting `conference_status_callback` URL - :param unicode conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback` - :param unicode recording_channels: Specify `mono` or `dual` recording channels - :param unicode recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes - :param unicode recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback` - :param unicode sip_auth_username: The SIP username used for authentication - :param unicode sip_auth_password: The SIP password for authentication - :param unicode region: The region where we should mix the conference audio - :param unicode conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available - :param unicode conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback` - :param unicode recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback` - :param unicode conference_recording_status_callback_event: The conference recording state changes that should generate a call to `conference_recording_status_callback` - :param bool coaching: Indicates if the participant changed to coach - :param unicode call_sid_to_coach: The SID of the participant who is being `coached` - :param unicode jitter_buffer_size: Jitter Buffer size for the connecting participant - :param unicode byoc: BYOC trunk SID (Beta) - :param unicode caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance - :returns: The 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), - 'Label': label, - '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), - 'Coaching': coaching, - 'CallSidToCoach': call_sid_to_coach, - 'JitterBufferSize': jitter_buffer_size, - 'Byoc': byoc, - 'CallerId': caller_id, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - ) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def stream(self, muted=values.unset, hold=values.unset, coaching=values.unset, - limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ParticipantInstance - :param bool muted: Whether to return only participants that are muted - :param bool hold: Whether to return only participants that are on hold - :param bool coaching: Whether to return only participants who are coaching another call - :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.conference.participant.ParticipantInstance] + :returns: The fetched ParticipantInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(muted=muted, hold=hold, coaching=coaching, page_size=limits['page_size'], ) + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance - return self._version.stream(page, limits['limit']) - def list(self, muted=values.unset, hold=values.unset, coaching=values.unset, - limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance - :param bool muted: Whether to return only participants that are muted - :param bool hold: Whether to return only participants that are on hold - :param bool coaching: Whether to return only participants who are coaching another call - :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 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.conference.participant.ParticipantInstance] + :returns: The updated ParticipantInstance """ - return list(self.stream( + 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, - limit=limit, - page_size=page_size, - )) + call_sid_to_coach=call_sid_to_coach, + ) - def page(self, muted=values.unset, hold=values.unset, coaching=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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 """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + 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, + ) - :param bool muted: Whether to return only participants that are muted - :param bool hold: Whether to return only participants that are on hold - :param bool coaching: Whether to return only participants who are coaching another call - :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 ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :returns: Machine friendly representation """ - data = values.of({ - 'Muted': muted, - 'Hold': hold, - 'Coaching': coaching, - '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(method='GET', uri=self._uri, params=data, ) - return ParticipantPage(self._version, response, self._solution) +class ParticipantContext(InstanceContext): - def get_page(self, target_url): + def __init__( + self, version: Version, account_sid: str, conference_sid: str, call_sid: str + ): """ - 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 + Initialize the ParticipantContext - :returns: Page of ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 or URL encoded label of the participant to fetch + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext - :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext + async def delete_async(self) -> bool: """ - return ParticipantContext( + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( self._version, - 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 __call__(self, call_sid): + async def fetch_async(self) -> ParticipantInstance: """ - Constructs a ParticipantContext + Asynchronous coroutine to fetch the ParticipantInstance - :param call_sid: The Call SID or URL encoded label of the participant to fetch - :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 = await self._version.fetch_async( + 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): + 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: """ - Provide a friendly representation + Update the ParticipantInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + 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({}) -class ParticipantPage(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 ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) - def __init__(self, version, response, 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 """ - Initialize the ParticipantPage - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param conference_sid: The SID of the conference the participant is in + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: 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 SID of the Account that created the resource to fetch - :param conference_sid: The SID of the conference with the participant to fetch - :param call_sid: The Call SID or URL encoded label of the participant to fetch + :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): + 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: """ - Fetch the ParticipantInstance + Create the ParticipantInstance - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.api.v2010.account.conference.participant.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) return ParticipantInstance( self._version, payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - 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, wait_url=values.unset, - wait_method=values.unset, beep_on_exit=values.unset, - end_conference_on_exit=values.unset, coaching=values.unset, - call_sid_to_coach=values.unset): + 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 """ - Update the ParticipantInstance - :param bool muted: Whether the participant should be muted - :param bool hold: Whether the participant should be on hold - :param unicode hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold - :param unicode hold_method: The HTTP method we should use to call hold_url - :param unicode announce_url: The URL we call using the `announce_method` for an announcement to the participant - :param unicode announce_method: The HTTP method we should use to call announce_url - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool beep_on_exit: Whether to play a notification beep to the conference when the participant exit - :param bool end_conference_on_exit: Whether to end the conference when the participant leaves - :param bool coaching: Indicates if the participant changed to coach - :param unicode call_sid_to_coach: The SID of the participant who is being `coached` + 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: The 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, - 'WaitUrl': wait_url, - 'WaitMethod': wait_method, - 'BeepOnExit': beep_on_exit, - 'EndConferenceOnExit': end_conference_on_exit, - 'Coaching': coaching, - 'CallSidToCoach': call_sid_to_coach, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return ParticipantInstance( self._version, payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - call_sid=self._solution['call_sid'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], ) - def delete(self): + 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]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + :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 __repr__(self): - """ - Provide a friendly representation - - :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.get('account_sid'), - 'call_sid': payload.get('call_sid'), - 'label': payload.get('label'), - 'call_sid_to_coach': payload.get('call_sid_to_coach'), - 'coaching': payload.get('coaching'), - 'conference_sid': payload.get('conference_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'end_conference_on_exit': payload.get('end_conference_on_exit'), - 'muted': payload.get('muted'), - 'hold': payload.get('hold'), - 'start_conference_on_enter': payload.get('start_conference_on_enter'), - 'status': payload.get('status'), - 'uri': payload.get('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 SID of the Account that created the resource - :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: The SID of the Call the resource is associated with - :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 label(self): - """ - :returns: The label of this participant - :rtype: unicode - """ - return self._properties['label'] + :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 call_sid_to_coach(self): - """ - :returns: The SID of the participant who is being `coached` - :rtype: unicode + :returns: Page of ParticipantInstance """ - return self._properties['call_sid_to_coach'] + 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 coaching(self): - """ - :returns: Indicates if the participant changed to coach - :rtype: bool - """ - return self._properties['coaching'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def conference_sid(self): - """ - :returns: The SID of the conference the participant is in - :rtype: unicode - """ - return self._properties['conference_sid'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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 end_conference_on_exit(self): - """ - :returns: Whether the conference ends when the participant leaves - :rtype: bool - """ - return self._properties['end_conference_on_exit'] + :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 muted(self): - """ - :returns: Whether the participant is muted - :rtype: bool + :returns: Page of ParticipantInstance """ - return self._properties['muted'] + 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 hold(self): - """ - :returns: Whether the participant is on hold - :rtype: bool - """ - return self._properties['hold'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def start_conference_on_enter(self): - """ - :returns: Whether the conference starts when the participant joins the conference - :rtype: bool - """ - return self._properties['start_conference_on_enter'] + headers["Accept"] = "application/json" - @property - def status(self): - """ - :returns: The status of the participant's call in a session - :rtype: ParticipantInstance.Status - """ - return self._properties['status'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of ParticipantInstance """ - Fetch the ParticipantInstance + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - :returns: The 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, wait_url=values.unset, - wait_method=values.unset, beep_on_exit=values.unset, - end_conference_on_exit=values.unset, coaching=values.unset, - call_sid_to_coach=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: Whether the participant should be muted - :param bool hold: Whether the participant should be on hold - :param unicode hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold - :param unicode hold_method: The HTTP method we should use to call hold_url - :param unicode announce_url: The URL we call using the `announce_method` for an announcement to the participant - :param unicode announce_method: The HTTP method we should use to call announce_url - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool beep_on_exit: Whether to play a notification beep to the conference when the participant exit - :param bool end_conference_on_exit: Whether to end the conference when the participant leaves - :param bool coaching: Indicates if the participant changed to coach - :param unicode call_sid_to_coach: The SID of the participant who is being `coached` + def get(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext - :returns: The 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, - 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 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 index 0e253fd3d2..12008ed37f 100644 --- a/twilio/rest/api/v2010/account/conference/recording.py +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -1,563 +1,718 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class RecordingInstance(InstanceResource): - def __init__(self, version, account_sid, conference_sid): - """ - Initialize the RecordingList + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param conference_sid: The Conference SID that identifies the conference associated with the recording + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingList - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingList - """ - super(RecordingList, self).__init__(version) + """ + :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") - # 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) + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_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 `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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"], + conference_sid=self._solution["conference_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.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']) + :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 `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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.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 `YYYY-MM-DD` value of the resources to read - :param date date_created: The `YYYY-MM-DD` value of the resources to read - :param date date_created_after: The `YYYY-MM-DD` value of the resources to read - :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.conference.recording.RecordingPage + :returns: The fetched RecordingInstance """ - data = 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RecordingPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "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 - :returns: Page of RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingPage + :returns: The fetched RecordingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RecordingPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": """ - Constructs a RecordingContext + Update the RecordingInstance - :param sid: The unique string that identifies the resource + :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.conference.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext + :returns: The updated RecordingInstance """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - sid=sid, + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, ) - def __call__(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 unique string that identifies the resource + :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.conference.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext + :returns: The updated RecordingInstance """ - return RecordingContext( - self._version, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], - sid=sid, + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, ) - 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, conference_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 SID of the Account that created the resource - :param conference_sid: The Conference SID that identifies the conference associated with the recording + Initialize the RecordingContext - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingPage - :rtype: twilio.rest.api.v2010.account.conference.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 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(RecordingPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 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.conference.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance + :returns: True if delete succeeds, False otherwise """ - return RecordingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - conference_sid=self._solution['conference_sid'], + + headers = 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 __repr__(self): + def fetch(self) -> RecordingInstance: """ - Provide a friendly representation + Fetch the RecordingInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched RecordingInstance """ - return '' + headers = values.of({}) -class RecordingContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, conference_sid, sid): + 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: """ - Initialize the RecordingContext + Asynchronous coroutine to fetch the RecordingInstance - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param conference_sid: Fetch by unique Conference SID for the recording - :param sid: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext + :returns: The fetched RecordingInstance """ - super(RecordingContext, self).__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) + headers = values.of({}) + + headers["Accept"] = "application/json" - def update(self, status, pause_behavior=values.unset): + 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 RecordingInstance.Status status: The new status of the recording - :param unicode pause_behavior: Whether to record during a pause + :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 - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance """ - data = values.of({'Status': status, 'PauseBehavior': pause_behavior, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], ) - def fetch(self): + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: """ - Fetch the RecordingInstance + Asynchronous coroutine to update the RecordingInstance - :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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"], + conference_sid=self._solution["conference_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" - ABSENT = "absent" + def __init__(self, version: Version, account_sid: str, conference_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 Conference Recording resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. - def __init__(self, version, payload, account_sid, conference_sid, sid=None): - """ - Initialize the RecordingInstance - - :returns: twilio.rest.api.v2010.account.conference.recording.RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance - """ - super(RecordingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'api_version': payload.get('api_version'), - 'call_sid': payload.get('call_sid'), - 'conference_sid': payload.get('conference_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'start_time': deserialize.rfc2822_datetime(payload.get('start_time')), - 'duration': payload.get('duration'), - 'sid': payload.get('sid'), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'status': payload.get('status'), - 'channels': deserialize.integer(payload.get('channels')), - 'source': payload.get('source'), - 'error_code': deserialize.integer(payload.get('error_code')), - 'encryption_details': payload.get('encryption_details'), - 'uri': payload.get('uri'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'account_sid': account_sid, - 'conference_sid': conference_sid, - 'sid': sid or self._properties['sid'], + "account_sid": account_sid, + "conference_sid": conference_sid, } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings.json".format( + **self._solution + ) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: RecordingContext for this RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingContext - """ - 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 + :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 account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 api_version(self): - """ - :returns: The API version used to create the recording - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode + 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['call_sid'] + 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 conference_sid(self): - """ - :returns: The Conference SID that identifies the conference associated with the recording - :rtype: unicode - """ - return self._properties['conference_sid'] + :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 date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the 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 = 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"], + ) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream_async(page, limits["limit"]) - @property - def start_time(self): - """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime + 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['start_time'] + 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 - """ - return self._properties['duration'] + :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, + ) + ) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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]: """ - return self._properties['sid'] + 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 price(self): - """ - :returns: The one-time cost of creating the recording. - :rtype: unicode + :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['price'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def price_unit(self): - """ - :returns: The currency used in the price property. - :rtype: unicode - """ - return self._properties['price_unit'] + :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 - @property - def status(self): - """ - :returns: The status of the recording - :rtype: RecordingInstance.Status + :returns: Page of RecordingInstance """ - return self._properties['status'] + 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 channels(self): - """ - :returns: The number of channels in the final recording file as an integer - :rtype: unicode - """ - return self._properties['channels'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def source(self): - """ - :returns: How the recording was created - :rtype: RecordingInstance.Source - """ - return self._properties['source'] + headers["Accept"] = "application/json" - @property - def error_code(self): - """ - :returns: More information about why the recording is missing, if status is `absent`. - :rtype: unicode - """ - return self._properties['error_code'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) - @property - def encryption_details(self): - """ - :returns: How to decrypt the recording. - :rtype: dict + 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['encryption_details'] + 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 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 RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + 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['uri'] + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) - def update(self, status, pause_behavior=values.unset): + async def get_page_async(self, target_url: str) -> RecordingPage: """ - Update the RecordingInstance + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :param RecordingInstance.Status status: The new status of the recording - :param unicode pause_behavior: Whether to record during a pause + :param target_url: API-generated URL for the requested results page - :returns: The updated RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance + :returns: Page of RecordingInstance """ - return self._proxy.update(status, pause_behavior=pause_behavior, ) + 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 the RecordingInstance + Constructs a RecordingContext - :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.conference.recording.RecordingInstance + :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 self._proxy.fetch() + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_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 Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. """ - return self._proxy.delete() + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_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/connect_app.py b/twilio/rest/api/v2010/account/connect_app.py index 693e46f812..689a2b184a 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -1,478 +1,690 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource + 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']) + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.delete_async() - return ConnectAppPage(self._version, response, self._solution) - - 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: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext + :returns: The fetched ConnectAppInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": """ - return ConnectAppContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + 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`. - def __call__(self, sid): + :returns: The updated ConnectAppInstance """ - Constructs a ConnectAppContext + 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, + ) - :param sid: The unique string that identifies the resource + 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: 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 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): + 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 SID of the Account that created the resource + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectAppInstance: """ - Fetch the ConnectAppInstance + Asynchronous coroutine to fetch the ConnectAppInstance + :returns: The fetched ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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: The URL to redirect the user to after authorization - :param unicode company_name: The company name to set for the Connect App - :param unicode deauthorize_callback_method: The HTTP method to use when calling deauthorize_callback_url - :param unicode deauthorize_callback_url: The URL to call to de-authorize the Connect App - :param unicode description: A description of the Connect App - :param unicode friendly_name: A string to describe the resource - :param unicode homepage_url: A public URL where users can obtain more information - :param ConnectAppInstance.Permission permissions: The set of permissions that your ConnectApp will request + :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 - :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), - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "AuthorizeRedirectUrl": authorize_redirect_url, + "CompanyName": company_name, + "DeauthorizeCallbackMethod": deauthorize_callback_method, + "DeauthorizeCallbackUrl": deauthorize_callback_url, + "Description": description, + "FriendlyName": friendly_name, + "HomepageUrl": homepage_url, + "Permissions": serialize.map(permissions, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ConnectAppInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the ConnectAppInstance + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated ConnectAppInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): - """ - Provide a friendly representation + 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.get('account_sid'), - 'authorize_redirect_url': payload.get('authorize_redirect_url'), - 'company_name': payload.get('company_name'), - 'deauthorize_callback_method': payload.get('deauthorize_callback_method'), - 'deauthorize_callback_url': payload.get('deauthorize_callback_url'), - 'description': payload.get('description'), - 'friendly_name': payload.get('friendly_name'), - 'homepage_url': payload.get('homepage_url'), - 'permissions': payload.get('permissions'), - 'sid': payload.get('sid'), - 'uri': payload.get('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): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def authorize_redirect_url(self): - """ - :returns: The URL to redirect the user to after authorization - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['authorize_redirect_url'] + return "" - @property - def company_name(self): - """ - :returns: The company name set for the Connect App - :rtype: unicode - """ - return self._properties['company_name'] - @property - def deauthorize_callback_method(self): - """ - :returns: The HTTP method we use to call deauthorize_callback_url - :rtype: unicode +class ConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['deauthorize_callback_method'] + 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_url(self): """ - :returns: The URL we call to de-authorize the Connect App - :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_url'] + 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: The description of the Connect 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['description'] + 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 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 string that you assigned to describe the 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[ConnectAppInstance]: """ - return self._properties['friendly_name'] + 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 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['homepage_url'] + 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 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 set of permissions that your ConnectApp requests - :rtype: ConnectAppInstance.Permission + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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['permissions'] + 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: The unique string that identifies the 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 = 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['sid'] + Asynchronously retrieve a single page of ConnectAppInstance 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 ConnectAppInstance """ - :returns: The URI of the resource, relative to `https://api.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 ConnectAppPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectAppPage: """ - return self._properties['uri'] + Retrieve a specific page of ConnectAppInstance 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 ConnectAppInstance """ - Fetch the ConnectAppInstance + response = self._version.domain.twilio.request("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) - :returns: The fetched ConnectAppInstance - :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance + async def get_page_async(self, target_url: str) -> ConnectAppPage: """ - return self._proxy.fetch() + 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 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): + :returns: Page of ConnectAppInstance """ - Update the ConnectAppInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) - :param unicode authorize_redirect_url: The URL to redirect the user to after authorization - :param unicode company_name: The company name to set for the Connect App - :param unicode deauthorize_callback_method: The HTTP method to use when calling deauthorize_callback_url - :param unicode deauthorize_callback_url: The URL to call to de-authorize the Connect App - :param unicode description: A description of the Connect App - :param unicode friendly_name: A string to describe the resource - :param unicode homepage_url: A public URL where users can obtain more information - :param ConnectAppInstance.Permission permissions: The set of permissions that your ConnectApp will request + def get(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext - :returns: The 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 delete(self): + def __call__(self, sid: str) -> ConnectAppContext: """ - Deletes the ConnectAppInstance + Constructs a ConnectAppContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. """ - return self._proxy.delete() + 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 f143212777..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,959 +1,1310 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource + 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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the IncomingPhoneNumber resources to read - :param unicode phone_number: The phone numbers of the IncomingPhoneNumber resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance + """ + if self._context is None: + self._context = IncomingPhoneNumberContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the IncomingPhoneNumberInstance - 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']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + async def delete_async(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. + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the IncomingPhoneNumber resources to read - :param unicode phone_number: The phone numbers of the IncomingPhoneNumber resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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 await self._proxy.delete_async() - 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): + def fetch(self) -> "IncomingPhoneNumberInstance": """ - Retrieve a single page of IncomingPhoneNumberInstance records from the API. - Request is executed immediately + Fetch the IncomingPhoneNumberInstance - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the IncomingPhoneNumber resources to read - :param unicode phone_number: The phone numbers of the IncomingPhoneNumber resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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 + :returns: The fetched IncomingPhoneNumberInstance """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance - return IncomingPhoneNumberPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched IncomingPhoneNumberInstance """ - Retrieve a specific page of IncomingPhoneNumberInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Update the IncomingPhoneNumberInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberPage + :returns: The updated IncomingPhoneNumberInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 IncomingPhoneNumberPage(self._version, response, self._solution) + 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. - 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, voice_receive_mode=values.unset, - bundle_sid=values.unset, phone_number=values.unset, - area_code=values.unset): + :returns: The updated IncomingPhoneNumberInstance """ - Create the IncomingPhoneNumberInstance - - :param unicode api_version: The API version to use for incoming calls made to the new phone number - :param unicode friendly_name: A string to describe the new phone number - :param unicode sms_application_sid: The SID of the application to handle SMS messages - :param unicode sms_fallback_method: HTTP method used with sms_fallback_url - :param unicode sms_fallback_url: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms url - :param unicode sms_url: The URL we should call when the new phone number receives an incoming SMS message - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the new phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: Status determining whether the new phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle calls to the new phone number - :param unicode identity_sid: The SID of the Identity resource to associate with the new phone number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param IncomingPhoneNumberInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode bundle_sid: The SID of the Bundle resource associated with number - :param unicode phone_number: The phone number to purchase in E.164 format - :param unicode area_code: The desired area code for the new phone number - - :returns: The 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, - 'VoiceReceiveMode': voice_receive_mode, - 'BundleSid': bundle_sid, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + 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: The unique string that identifies the resource + # 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: The unique string that identifies the resource - :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 SID of the Account that created the resource - :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 + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - :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) - - # 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, - bundle_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 SID of the Account that created the resource to update - :param unicode api_version: The API version to use for incoming calls made to the phone number - :param unicode friendly_name: A string to describe the 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: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_url: The URL we should call when the phone number receives an incoming SMS message - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: Whether the phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle phone calls to the phone number - :param IncomingPhoneNumberInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode identity_sid: Unique string that identifies the identity associated with number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param unicode bundle_sid: The SID of the Bundle resource associated with number + :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 - :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, - 'BundleSid': bundle_sid, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return IncomingPhoneNumberInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def fetch(self): - """ - Fetch the 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 fetched IncomingPhoneNumberInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberInstance + :returns: The updated IncomingPhoneNumberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return IncomingPhoneNumberInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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.get('account_sid'), - 'address_sid': payload.get('address_sid'), - 'address_requirements': payload.get('address_requirements'), - 'api_version': payload.get('api_version'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'identity_sid': payload.get('identity_sid'), - 'phone_number': payload.get('phone_number'), - 'origin': payload.get('origin'), - 'sid': payload.get('sid'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'voice_receive_mode': payload.get('voice_receive_mode'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'emergency_status': payload.get('emergency_status'), - 'emergency_address_sid': payload.get('emergency_address_sid'), - 'bundle_sid': payload.get('bundle_sid'), - 'status': payload.get('status'), - } + :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 SID of the Account that created the resource - :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: The SID of the Address resource associated with the phone number - :rtype: unicode """ - return self._properties['address_sid'] + super().__init__(version) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :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): + 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: """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - return self._properties['api_version'] + Create the IncomingPhoneNumberInstance - @property - def beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] + :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). - @property - def capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode + :returns: The created IncomingPhoneNumberInstance """ - return self._properties['capabilities'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + 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 date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + headers["Accept"] = "application/json" - @property - def identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode - """ - return self._properties['identity_sid'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def origin(self): - """ - :returns: The phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + 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). - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created IncomingPhoneNumberInstance """ - return self._properties['sid'] - @property - def sms_application_sid(self): - """ - :returns: The SID of the application that handles SMS messages sent to the phone number - :rtype: unicode - """ - return self._properties['sms_application_sid'] + 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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_fallback_url - :rtype: unicode - """ - return self._properties['sms_fallback_method'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sms_fallback_url(self): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + headers["Accept"] = "application/json" - @property - def sms_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sms_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your 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['status_callback'] + 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_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_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 trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['trunk_sid'] + 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 uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + return self._version.stream(page, limits["limit"]) - @property - def voice_receive_mode(self): + 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]: """ - :returns: The voice_receive_mode - :rtype: IncomingPhoneNumberInstance.VoiceReceiveMode - """ - return self._properties['voice_receive_mode'] + 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 voice_application_sid(self): - """ - :returns: The SID of the application that handles calls to the phone 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :rtype: bool + :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( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + return self._version.stream_async(page, limits["limit"]) - @property - def voice_fallback_url(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 URL we call when an error occurs in TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + 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_method(self): - """ - :returns: The HTTP method used with the voice_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 list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Asynchronously lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IncomingPhoneNumberPage: """ - return self._properties['voice_method'] + Retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately - @property - def voice_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: The URL we call when the phone number receives a call - :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_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 emergency_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 IncomingPhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IncomingPhoneNumberPage: """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: IncomingPhoneNumberInstance.EmergencyStatus + 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['emergency_status'] + response = self._version.domain.twilio.request("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) - @property - def emergency_address_sid(self): + async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: """ - :returns: The emergency address configuration to use for emergency calling - :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['emergency_address_sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) @property - def bundle_sid(self): + def local(self) -> LocalList: """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + Access the local """ - return self._properties['bundle_sid'] + if self._local is None: + self._local = LocalList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._local @property - def status(self): - """ - :returns: The status - :rtype: unicode - """ - return self._properties['status'] - - 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, - bundle_sid=values.unset): + def mobile(self) -> MobileList: """ - Update the IncomingPhoneNumberInstance - - :param unicode account_sid: The SID of the Account that created the resource to update - :param unicode api_version: The API version to use for incoming calls made to the phone number - :param unicode friendly_name: A string to describe the 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: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_url: The URL we should call when the phone number receives an incoming SMS message - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param IncomingPhoneNumberInstance.EmergencyStatus emergency_status: Whether the phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle phone calls to the phone number - :param IncomingPhoneNumberInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode identity_sid: Unique string that identifies the identity associated with number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param unicode bundle_sid: The SID of the Bundle resource associated with number - - :returns: The 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, - bundle_sid=bundle_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 the IncomingPhoneNumberInstance - - :returns: The 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 d5e66e4f73..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,482 +1,602 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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" + ) - def __init__(self, version, account_sid, resource_sid): + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssignedAddOnContext] = None + + @property + def _proxy(self) -> "AssignedAddOnContext": """ - 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 SID of the Account that created the resource - :param resource_sid: The SID of the Phone Number that 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + @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): + """ + 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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 the AssignedAddOnInstance + Deletes the AssignedAddOnInstance - :param unicode installed_add_on_sid: The SID that identifies the Add-on installation - :returns: The 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(method='POST', uri=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 string that identifies the resource - :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 string that identifies the resource - :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" + + 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"], + ) - def __init__(self, version, response, solution): + @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 SID of the Account that created the resource - :param resource_sid: The SID of the Phone Number that 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 SID of the Account that created the resource to fetch - :param resource_sid: The SID of the Phone Number that installed this Add-on - :param sid: The unique string that identifies the 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 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 the AssignedAddOnInstance + Create the AssignedAddOnInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'resource_sid': payload.get('resource_sid'), - 'friendly_name': payload.get('friendly_name'), - 'description': payload.get('description'), - 'configuration': payload.get('configuration'), - 'unique_name': payload.get('unique_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'uri': payload.get('uri'), - 'subresource_uris': payload.get('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): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Phone Number that 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): - """ - :returns: The string that you assigned to describe the resource - :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, + ) -> AssignedAddOnPage: """ - 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: A JSON string that represents 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: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource 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 of the resource, relative to `https://api.twilio.com` - :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: A list of related resources identified by their relative 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 the AssignedAddOnInstance + Asynchronously retrieve a specific page of AssignedAddOnInstance records from the API. + Request is executed immediately - :returns: The fetched AssignedAddOnInstance - :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnInstance + :param target_url: API-generated URL for the requested results page + + :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 9d15620af4..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,414 +1,484 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :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.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']) + :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) - 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 string that identifies the resource - :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 string that identifies the resource - :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 SID of the Account that created the resource - :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.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 SID of the 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 unique string that identifies the 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 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 the AssignedAddOnExtensionInstance + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json".format( + **self._solution + ) - :returns: The 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]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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. - 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'], - ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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[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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'resource_sid': payload.get('resource_sid'), - 'assigned_add_on_sid': payload.get('assigned_add_on_sid'), - 'friendly_name': payload.get('friendly_name'), - 'product_name': payload.get('product_name'), - 'unique_name': payload.get('unique_name'), - 'uri': payload.get('uri'), - 'enabled': payload.get('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): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Phone Number to which the Add-on is assigned - :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 assigned_add_on_sid(self): - """ - :returns: The SID that uniquely identifies the assigned Add-on installation - :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, + ) -> AssignedAddOnExtensionPage: """ - 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: The string that you assigned to describe the resource - :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 string that you assigned to describe the Product this Extension is used within - :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: An application-defined string that uniquely identifies the resource - :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 of the resource, relative to `https://api.twilio.com` - :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: Whether 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 the AssignedAddOnExtensionInstance + Constructs a AssignedAddOnExtensionContext - :returns: The 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 1324956879..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,594 +1,672 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - - :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) +class LocalInstance(InstanceResource): - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json'.format(**self._solution) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - 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. + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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 EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - :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 VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + """ + :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']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def __repr__(self) -> str: """ - Lists LocalInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance] - """ - 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): + :returns: Machine friendly representation """ - Retrieve a single page of LocalInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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.incoming_phone_number.local.LocalPage - """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - bundle_sid=values.unset): - """ - Create the LocalInstance - - :param unicode phone_number: The phone number to purchase in E.164 format - :param unicode api_version: The API version to use for incoming calls made to the new phone number - :param unicode friendly_name: A string to describe the new phone number - :param unicode sms_application_sid: The SID of the application to handle SMS messages - :param unicode sms_fallback_method: The HTTP method we use to call status_callback - :param unicode sms_fallback_url: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms url - :param unicode sms_url: The URL we should call when the new phone number receives an incoming SMS message - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the new phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param unicode identity_sid: The SID of the Identity resource to associate with the new phone number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param LocalInstance.EmergencyStatus emergency_status: Status determining whether the new phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle calls to the new phone number - :param LocalInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode bundle_sid: The SID of the Bundle resource associated with number - - :returns: The 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, - 'EmergencyStatus': emergency_status, - 'EmergencyAddressSid': emergency_address_sid, - 'TrunkSid': trunk_sid, - 'VoiceReceiveMode': voice_receive_mode, - 'BundleSid': bundle_sid, - }) - - payload = self._version.create(method='POST', uri=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 SID of the Account that created the 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 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): + 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: """ - Build an instance of LocalInstance - - :param dict payload: Payload response from the API + Create the LocalInstance - :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'], ) + :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. - def __repr__(self): + :returns: The created LocalInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class LocalInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + 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. - def __init__(self, version, payload, account_sid): + :returns: The created LocalInstance """ - 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.get('account_sid'), - 'address_sid': payload.get('address_sid'), - 'address_requirements': payload.get('address_requirements'), - 'api_version': payload.get('api_version'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'identity_sid': payload.get('identity_sid'), - 'phone_number': payload.get('phone_number'), - 'origin': payload.get('origin'), - 'sid': payload.get('sid'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'emergency_status': payload.get('emergency_status'), - 'emergency_address_sid': payload.get('emergency_address_sid'), - 'bundle_sid': payload.get('bundle_sid'), - } + 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"}) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: LocalInstance.AddressRequirement - """ - return self._properties['address_requirements'] + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :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['api_version'] + 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 beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] + :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 capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['capabilities'] + 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 date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was 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, + 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]: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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 friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + :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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['identity_sid'] + 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 phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + return self._version.stream_async(page, limits["limit"]) - @property - def origin(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 phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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 sms_application_sid(self): - """ - :returns: The SID of the Application resource to handle SMS messages - :rtype: unicode - """ - return self._properties['sms_application_sid'] + 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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_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 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: """ - return self._properties['sms_fallback_method'] + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately - @property - def sms_fallback_url(self): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + :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_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['sms_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 sms_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) - @property - def trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - return self._properties['trunk_sid'] + 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 uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + :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 voice_application_sid(self): - """ - :returns: The SID of the application that handles calls to the phone number - :rtype: unicode + :returns: Page of LocalInstance """ - return self._properties['voice_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 voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :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 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: The URL we call when an error occurs in TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + 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_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode + def get_page(self, target_url: str) -> LocalPage: """ - return self._properties['voice_method'] + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The URL we call when this phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: LocalInstance.EmergencyStatus + :returns: Page of LocalInstance """ - return self._properties['emergency_status'] + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) - @property - def emergency_address_sid(self): + async def get_page_async(self, target_url: str) -> LocalPage: """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode - """ - return self._properties['emergency_address_sid'] + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately - @property - def bundle_sid(self): - """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance """ - return self._properties['bundle_sid'] + 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 490295ed6d..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,594 +1,676 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - - :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) +class MobileInstance(InstanceResource): - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json'.format(**self._solution) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - 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. + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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 EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - :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 VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + """ + :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']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def __repr__(self) -> str: """ - Lists MobileInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance] - """ - 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): + :returns: Machine friendly representation """ - Retrieve a single page of MobileInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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.incoming_phone_number.mobile.MobilePage - """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - bundle_sid=values.unset): - """ - Create the MobileInstance - - :param unicode phone_number: The phone number to purchase in E.164 format - :param unicode api_version: The API version to use for incoming calls made to the new phone number - :param unicode friendly_name: A string to describe the new phone number - :param unicode sms_application_sid: The SID of the application to handle SMS messages - :param unicode sms_fallback_method: HTTP method used with sms_fallback_url - :param unicode sms_fallback_url: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms url - :param unicode sms_url: The URL we should call when the new phone number receives an incoming SMS message - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the new phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param unicode identity_sid: The SID of the Identity resource to associate with the new phone number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param MobileInstance.EmergencyStatus emergency_status: Status determining whether the new phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle calls to the new phone number - :param MobileInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode bundle_sid: The SID of the Bundle resource associated with number - - :returns: The 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, - 'EmergencyStatus': emergency_status, - 'EmergencyAddressSid': emergency_address_sid, - 'TrunkSid': trunk_sid, - 'VoiceReceiveMode': voice_receive_mode, - 'BundleSid': bundle_sid, - }) - - payload = self._version.create(method='POST', uri=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 SID of the Account that created the 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 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): + 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: """ - Build an instance of MobileInstance - - :param dict payload: Payload response from the API + Create the MobileInstance - :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'], ) + :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. - def __repr__(self): + :returns: The created MobileInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class MobileInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + 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. - def __init__(self, version, payload, account_sid): + :returns: The created MobileInstance """ - 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.get('account_sid'), - 'address_sid': payload.get('address_sid'), - 'address_requirements': payload.get('address_requirements'), - 'api_version': payload.get('api_version'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'identity_sid': payload.get('identity_sid'), - 'phone_number': payload.get('phone_number'), - 'origin': payload.get('origin'), - 'sid': payload.get('sid'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'emergency_status': payload.get('emergency_status'), - 'emergency_address_sid': payload.get('emergency_address_sid'), - 'bundle_sid': payload.get('bundle_sid'), - } + 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"}) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: MobileInstance.AddressRequirement - """ - return self._properties['address_requirements'] + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :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['api_version'] + 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 beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] + :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 capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['capabilities'] + 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 date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was 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, + 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]: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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 friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + :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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['identity_sid'] + 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 phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + return self._version.stream_async(page, limits["limit"]) - @property - def origin(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 phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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 sms_application_sid(self): - """ - :returns: The SID of the application that handles SMS messages sent to the phone number - :rtype: unicode - """ - return self._properties['sms_application_sid'] + 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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_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 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: """ - return self._properties['sms_fallback_method'] + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately - @property - def sms_fallback_url(self): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + :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_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['sms_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 sms_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) - @property - def trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - return self._properties['trunk_sid'] + 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 uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + :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 voice_application_sid(self): - """ - :returns: The SID of the application that handles calls to the phone number - :rtype: unicode + :returns: Page of MobileInstance """ - return self._properties['voice_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 voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :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 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: The URL we call when an error occurs in TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + 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_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode + def get_page(self, target_url: str) -> MobilePage: """ - return self._properties['voice_method'] + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: MobileInstance.EmergencyStatus + :returns: Page of MobileInstance """ - return self._properties['emergency_status'] + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) - @property - def emergency_address_sid(self): + async def get_page_async(self, target_url: str) -> MobilePage: """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode - """ - return self._properties['emergency_address_sid'] + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately - @property - def bundle_sid(self): - """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance """ - return self._properties['bundle_sid'] + 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 99ac74b50b..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,594 +1,676 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - - :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) +class TollFreeInstance(InstanceResource): - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json'.format(**self._solution) + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" - 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. + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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 EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" - :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 VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" - page = self.page( - beta=beta, - friendly_name=friendly_name, - phone_number=phone_number, - origin=origin, - page_size=limits['page_size'], + """ + :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']) - - def list(self, beta=values.unset, friendly_name=values.unset, - phone_number=values.unset, origin=values.unset, limit=None, - page_size=None): + def __repr__(self) -> str: """ - Lists TollFreeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.incoming_phone_number.toll_free.TollFreeInstance] - """ - 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): + :returns: Machine friendly representation """ - Retrieve a single page of TollFreeInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param bool beta: Whether to include new phone numbers - :param unicode friendly_name: A string that identifies the resources to read - :param unicode phone_number: The phone numbers of the resources to read - :param unicode origin: Include phone numbers based on their origin. By default, phone numbers of all origin are included. - :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.incoming_phone_number.toll_free.TollFreePage - """ - data = values.of({ - 'Beta': beta, - 'FriendlyName': friendly_name, - 'PhoneNumber': phone_number, - 'Origin': origin, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - emergency_status=values.unset, emergency_address_sid=values.unset, - trunk_sid=values.unset, voice_receive_mode=values.unset, - bundle_sid=values.unset): - """ - Create the TollFreeInstance - - :param unicode phone_number: The phone number to purchase in E.164 format - :param unicode api_version: The API version to use for incoming calls made to the new phone number - :param unicode friendly_name: A string to describe the new phone number - :param unicode sms_application_sid: The SID of the application to handle SMS messages - :param unicode sms_fallback_method: HTTP method used with sms_fallback_url - :param unicode sms_fallback_url: The URL we call when an error occurs while executing TwiML - :param unicode sms_method: The HTTP method to use with sms_url - :param unicode sms_url: The URL we should call when the new phone number receives an incoming SMS message - :param unicode status_callback: The URL to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param unicode voice_application_sid: The SID of the application to handle the new phone number - :param bool voice_caller_id_lookup: Whether to lookup the caller's name - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we will call when an error occurs in TwiML - :param unicode voice_method: The HTTP method used with the voice_url - :param unicode voice_url: The URL we should call when the phone number receives a call - :param unicode identity_sid: The SID of the Identity resource to associate with the new phone number - :param unicode address_sid: The SID of the Address resource associated with the phone number - :param TollFreeInstance.EmergencyStatus emergency_status: Status determining whether the new phone number is enabled for emergency calling - :param unicode emergency_address_sid: The emergency address configuration to use for emergency calling - :param unicode trunk_sid: SID of the trunk to handle calls to the new phone number - :param TollFreeInstance.VoiceReceiveMode voice_receive_mode: Incoming call type: fax or voice - :param unicode bundle_sid: The SID of the Bundle resource associated with number - - :returns: The 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, - 'EmergencyStatus': emergency_status, - 'EmergencyAddressSid': emergency_address_sid, - 'TrunkSid': trunk_sid, - 'VoiceReceiveMode': voice_receive_mode, - 'BundleSid': bundle_sid, - }) - - payload = self._version.create(method='POST', uri=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 SID of the Account that created the 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 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): + 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: """ - Build an instance of TollFreeInstance - - :param dict payload: Payload response from the API + Create 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 - """ - return TollFreeInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + :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. - def __repr__(self): + :returns: The created TollFreeInstance """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str - """ - return '' + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class TollFreeInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - class AddressRequirement(object): - NONE = "none" - ANY = "any" - LOCAL = "local" - FOREIGN = "foreign" + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - class EmergencyStatus(object): - ACTIVE = "Active" - INACTIVE = "Inactive" + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class VoiceReceiveMode(object): - VOICE = "voice" - FAX = "fax" + 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. - def __init__(self, version, payload, account_sid): + :returns: The created TollFreeInstance """ - 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.get('account_sid'), - 'address_sid': payload.get('address_sid'), - 'address_requirements': payload.get('address_requirements'), - 'api_version': payload.get('api_version'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'identity_sid': payload.get('identity_sid'), - 'phone_number': payload.get('phone_number'), - 'origin': payload.get('origin'), - 'sid': payload.get('sid'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'trunk_sid': payload.get('trunk_sid'), - 'uri': payload.get('uri'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'emergency_status': payload.get('emergency_status'), - 'emergency_address_sid': payload.get('emergency_address_sid'), - 'bundle_sid': payload.get('bundle_sid'), - } + 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"}) - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def address_sid(self): - """ - :returns: The SID of the Address resource associated with the phone number - :rtype: unicode - """ - return self._properties['address_sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def address_requirements(self): - """ - :returns: Whether the phone number requires an Address registered with Twilio. - :rtype: TollFreeInstance.AddressRequirement - """ - return self._properties['address_requirements'] + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def api_version(self): - """ - :returns: The API version used to start a new TwiML session - :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['api_version'] + 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 beta(self): - """ - :returns: Whether the phone number is new to the Twilio platform - :rtype: bool - """ - return self._properties['beta'] + :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 capabilities(self): - """ - :returns: Indicate if a phone can receive calls or messages - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['capabilities'] + 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 date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was 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, + 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]: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + 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 friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + :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 identity_sid(self): - """ - :returns: The SID of the Identity resource associated with number - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['identity_sid'] + 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 phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + return self._version.stream_async(page, limits["limit"]) - @property - def origin(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 phone number's origin. Can be twilio or hosted. - :rtype: unicode - """ - return self._properties['origin'] + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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 sms_application_sid(self): - """ - :returns: The SID of the application that handles SMS messages sent to the phone number - :rtype: unicode - """ - return self._properties['sms_application_sid'] + 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 sms_fallback_method(self): - """ - :returns: The HTTP method used with sms_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 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: """ - return self._properties['sms_fallback_method'] + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately - @property - def sms_fallback_url(self): - """ - :returns: The URL that we call when an error occurs while retrieving or executing the TwiML - :rtype: unicode - """ - return self._properties['sms_fallback_url'] + :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_method(self): - """ - :returns: The HTTP method to use with sms_url - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['sms_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 sms_url(self): - """ - :returns: The URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) - @property - def trunk_sid(self): - """ - :returns: The SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - return self._properties['trunk_sid'] + 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 uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + :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 voice_application_sid(self): - """ - :returns: The SID of the application that handles calls to the phone number - :rtype: unicode + :returns: Page of TollFreeInstance """ - return self._properties['voice_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 voice_caller_id_lookup(self): - """ - :returns: Whether to lookup the caller's name - :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 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: The URL we call when an error occurs in TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + 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_method(self): - """ - :returns: The HTTP method used with the voice_url - :rtype: unicode + def get_page(self, target_url: str) -> TollFreePage: """ - return self._properties['voice_method'] + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately - @property - def voice_url(self): - """ - :returns: The URL we call when the phone number receives a call - :rtype: unicode - """ - return self._properties['voice_url'] + :param target_url: API-generated URL for the requested results page - @property - def emergency_status(self): - """ - :returns: Whether the phone number is enabled for emergency calling - :rtype: TollFreeInstance.EmergencyStatus + :returns: Page of TollFreeInstance """ - return self._properties['emergency_status'] + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) - @property - def emergency_address_sid(self): + async def get_page_async(self, target_url: str) -> TollFreePage: """ - :returns: The emergency address configuration to use for emergency calling - :rtype: unicode - """ - return self._properties['emergency_address_sid'] + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately - @property - def bundle_sid(self): - """ - :returns: The SID of the Bundle resource associated with number - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance """ - return self._properties['bundle_sid'] + 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 d0094d8035..8b18dbd4ba 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -1,371 +1,566 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 unique string that identifies the resource + :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 unique string that identifies the resource + :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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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" - def fetch(self): + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> KeyInstance: """ - Fetch the KeyInstance + Asynchronous coroutine to fetch the KeyInstance + :returns: The fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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: A string to describe the resource + :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 - :rtype: twilio.rest.api.v2010.account.key.KeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return KeyInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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 + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: + """ + Build an instance of KeyInstance + + :param payload: Payload response from the API """ - return self._version.delete(method='DELETE', uri=self._uri, ) + return KeyInstance( + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class KeyInstance(InstanceResource): - """ """ +class KeyList(ListResource): - def __init__(self, version, payload, account_sid, sid=None): + def __init__(self, version: Version, account_sid: str): """ - Initialize the KeyInstance + 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. - :returns: twilio.rest.api.v2010.account.key.KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance """ - super(KeyInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('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 unique string that identifies the 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[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 + """ + return 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]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Asynchronously lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return 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, + ) -> KeyPage: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + Retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance """ - 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 = 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: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + Asynchronously retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance """ - return self._properties['date_updated'] + data = values.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 KeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> KeyPage: """ - Fetch the KeyInstance + Retrieve a specific page of KeyInstance records from the API. + Request is executed immediately - :returns: The fetched KeyInstance - :rtype: twilio.rest.api.v2010.account.key.KeyInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return KeyPage(self._version, response, self._solution) - def update(self, friendly_name=values.unset): + async def get_page_async(self, target_url: str) -> KeyPage: """ - Update the KeyInstance + Asynchronously retrieve a specific page of KeyInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource + :param target_url: API-generated URL for the requested results page - :returns: The 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 f0e5b5d7da..d5369d11ce 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -1,702 +1,1014 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource + 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, - attempt=values.unset, validity_period=values.unset, - force_delivery=values.unset, content_retention=values.unset, - address_retention=values.unset, smart_encoded=values.unset, - persistent_action=values.unset, from_=values.unset, - messaging_service_sid=values.unset, body=values.unset, - media_url=values.unset): - """ - Create the MessageInstance + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" - :param unicode to: The destination phone number - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode application_sid: The application to use for callbacks - :param unicode max_price: The total maximum price up to 4 decimal places in US dollars acceptable for the message to be delivered. - :param bool provide_feedback: Whether to confirm delivery of the message - :param unicode attempt: Total numer of attempts made , this inclusive to send out the message - :param unicode validity_period: The number of seconds that the message can remain in our outgoing queue. - :param bool force_delivery: Reserved - :param MessageInstance.ContentRetention content_retention: Determines if the message content can be stored or redacted based on privacy settings - :param MessageInstance.AddressRetention address_retention: Determines if the address can be stored or obfuscated based on privacy settings - :param bool smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them - :param unicode persistent_action: Rich actions for Channels Messages. - :param unicode from_: The phone number that initiated the message - :param unicode messaging_service_sid: The SID of the Messaging Service you want to associate with the message. - :param unicode body: The text of the message you want to send. Can be up to 1,600 characters in length. - :param unicode media_url: The URL of the media to send with the message + class ScheduleType(object): + FIXED = "fixed" - :returns: The 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, - 'Attempt': attempt, - 'ValidityPeriod': validity_period, - 'ForceDelivery': force_delivery, - 'ContentRetention': content_retention, - 'AddressRetention': address_retention, - 'SmartEncoded': smart_encoded, - 'PersistentAction': serialize.map(persistent_action, lambda e: e), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return MessageInstance(self._version, payload, account_sid=self._solution['account_sid'], ) - - 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): + class Status(object): + QUEUED = "queued" + SENDING = "sending" + SENT = "sent" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + RECEIVING = "receiving" + RECEIVED = "received" + ACCEPTED = "accepted" + SCHEDULED = "scheduled" + READ = "read" + PARTIALLY_DELIVERED = "partially_delivered" + CANCELED = "canceled" + + class TrafficType(object): + FREE = "free" + + class UpdateStatus(object): + CANCELED = "canceled" + + """ + :ivar body: The text content of the message + :ivar num_segments: The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn't yet been assigned. + :ivar direction: + :ivar from_: The sender's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent. + :ivar to: The recipient's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`) + :ivar date_updated: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated + :ivar price: The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details. + :ivar error_message: The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar uri: The URI of the Message resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource + :ivar num_media: The number of media files associated with the Message resource. + :ivar status: + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used. + :ivar sid: The unique, Twilio-provided string that identifies the Message resource. + :ivar date_sent: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL. + :ivar date_created: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created + :ivar error_code: The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar api_version: The API version used to process the Message + :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.body: Optional[str] = payload.get("body") + self.num_segments: Optional[str] = payload.get("num_segments") + self.direction: Optional["MessageInstance.Direction"] = payload.get("direction") + self.from_: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.price: Optional[str] = payload.get("price") + self.error_message: Optional[str] = payload.get("error_message") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.num_media: Optional[str] = payload.get("num_media") + self.status: Optional["MessageInstance.Status"] = payload.get("status") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_sent: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_sent") + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.api_version: Optional[str] = payload.get("api_version") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": """ - 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 sent 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']) + :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 sent 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 sent 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 + :returns: The fetched MessageInstance """ - data = 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, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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: The unique string that identifies the resource + :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: The unique string that identifies the resource + 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 SID of the Account that created the resource + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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(method='DELETE', uri=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 the MessageInstance + Asynchronous coroutine to fetch the MessageInstance + :returns: The fetched MessageInstance - :rtype: twilio.rest.api.v2010.account.message.MessageInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 text of the message you want to send + :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 - :rtype: twilio.rest.api.v2010.account.message.MessageInstance """ - data = values.of({'Body': body, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return MessageInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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 + + :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.media.MediaList - :rtype: twilio.rest.api.v2010.account.message.media.MediaList + :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 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" +class MessagePage(Page): - class Direction(object): - INBOUND = "inbound" - OUTBOUND_API = "outbound-api" - OUTBOUND_CALL = "outbound-call" - OUTBOUND_REPLY = "outbound-reply" + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance - class ContentRetention(object): - RETAIN = "retain" + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - class AddressRetention(object): - RETAIN = "retain" + def __repr__(self) -> str: + """ + Provide a friendly representation - class TrafficType(object): - FREE = "free" + :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 = { - 'body': payload.get('body'), - 'num_segments': payload.get('num_segments'), - 'direction': payload.get('direction'), - 'from_': payload.get('from'), - 'to': payload.get('to'), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'price': payload.get('price'), - 'error_message': payload.get('error_message'), - 'uri': payload.get('uri'), - 'account_sid': payload.get('account_sid'), - 'num_media': payload.get('num_media'), - 'status': payload.get('status'), - 'messaging_service_sid': payload.get('messaging_service_sid'), - 'sid': payload.get('sid'), - 'date_sent': deserialize.rfc2822_datetime(payload.get('date_sent')), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'error_code': deserialize.integer(payload.get('error_code')), - 'price_unit': payload.get('price_unit'), - 'api_version': payload.get('api_version'), - 'subresource_uris': payload.get('subresource_uris'), - } - # 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 body(self): """ - :returns: The message text - :rtype: unicode - """ - return self._properties['body'] + super().__init__(version) - @property - def num_segments(self): - """ - :returns: The number of messages used to deliver the message body - :rtype: unicode + # 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: """ - return self._properties['num_segments'] + Create the MessageInstance - @property - def direction(self): - """ - :returns: The direction of the message - :rtype: MessageInstance.Direction - """ - return self._properties['direction'] + :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). - @property - def from_(self): - """ - :returns: The phone number that initiated the message - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['from_'] - @property - def to(self): - """ - :returns: The phone number that received the message - :rtype: unicode - """ - return self._properties['to'] + 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 date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def price(self): - """ - :returns: The amount billed for the message - :rtype: unicode - """ - return self._properties['price'] + headers["Accept"] = "application/json" - @property - def error_message(self): - """ - :returns: The description of the error_code - :rtype: unicode - """ - return self._properties['error_message'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + async def create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). - @property - def num_media(self): - """ - :returns: The number of media files associated with the message - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['num_media'] - @property - def status(self): - """ - :returns: The status of the message - :rtype: MessageInstance.Status - """ - return self._properties['status'] + 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 messaging_service_sid(self): - """ - :returns: The SID of the Messaging Service used with the message. - :rtype: unicode - """ - return self._properties['messaging_service_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def date_sent(self): - """ - :returns: The RFC 2822 date and time in GMT when the message was sent - :rtype: datetime - """ - return self._properties['date_sent'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def error_code(self): - """ - :returns: The error code 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['error_code'] + 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 price_unit(self): - """ - :returns: The currency in which price is measured - :rtype: unicode + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['price_unit'] + 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 api_version(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: """ - :returns: The API version used to process the message - :rtype: unicode + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['api_version'] + 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 subresource_uris(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - :returns: A list of related resources identified by their relative URIs - :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['subresource_uris'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - def delete(self): + :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 """ - 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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) - def fetch(self): + def get_page(self, target_url: str) -> MessagePage: """ - Fetch the MessageInstance + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :returns: The 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 text of the message you want to send + :param target_url: API-generated URL for the requested results page - :returns: The 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 517319508b..cda2de2ff6 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -1,197 +1,170 @@ -# coding=utf-8 r""" -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 FeedbackList(ListResource): - """ """ - - def __init__(self, version, account_sid, message_sid): - """ - Initialize the FeedbackList + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param message_sid: The SID of the Message resource for which the feedback was provided + Twilio - Api + This is the public Twilio REST API. - :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList - """ - super(FeedbackList, self).__init__(version) + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - # 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) +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values - def create(self, outcome=values.unset): - """ - Create the FeedbackInstance +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - :param FeedbackInstance.Outcome outcome: Whether the feedback has arrived - :returns: The created FeedbackInstance - :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance - """ - data = values.of({'Outcome': outcome, }) +class FeedbackInstance(InstanceResource): - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + class Outcome(object): + CONFIRMED = "confirmed" + UNCONFIRMED = "unconfirmed" - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - message_sid=self._solution['message_sid'], + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this MessageFeedback resource. + :ivar message_sid: The SID of the Message resource associated with this MessageFeedback resource. + :ivar outcome: + :ivar date_created: The date and time in GMT when this MessageFeedback resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this MessageFeedback resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.outcome: Optional["FeedbackInstance.Outcome"] = payload.get("outcome") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } - def __repr__(self): + 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 SID of the Account that created the resource - :param message_sid: The SID of the Message resource for which the feedback was provided + :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 - - :param dict payload: Payload response from the API + Create the FeedbackInstance - :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" - UNCONFIRMED = "unconfirmed" + 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.get('account_sid'), - 'message_sid': payload.get('message_sid'), - 'outcome': payload.get('outcome'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'uri': payload.get('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 SID of the Account that created the resource - :rtype: unicode + :returns: The created FeedbackInstance """ - return self._properties['account_sid'] - @property - def message_sid(self): - """ - :returns: The SID of the Message resource for which the feedback was provided - :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: Whether the feedback has arrived - :rtype: FeedbackInstance.Outcome - """ - return self._properties['outcome'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last 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 of the resource, relative to `https://api.twilio.com` - :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 4db076f3e2..b5d2926d12 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -1,422 +1,564 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created this resource - :param message_sid: The unique string that identifies the resource + 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: Only include media that was created on this date - :param datetime date_created: Only include media that was created on this date - :param datetime date_created_after: Only include media that was created on this 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 = 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']) + :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: Only include media that was created on this date - :param datetime date_created: Only include media that was created on this date - :param datetime date_created_after: Only include media that was created on this 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.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: Only include media that was created on this date - :param datetime date_created: Only include media that was created on this date - :param datetime date_created_after: Only include media that was created on this 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 MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaPage + :returns: The fetched MediaInstance """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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: The unique string that identifies this resource + 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: The unique string that identifies this resource - :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 SID of the Account that created this resource - :param message_sid: The unique string that identifies the resource - :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 SID of the Account that created the resource(s) to fetch - :param message_sid: The SID of the Message resource that this Media resource belongs to - :param sid: The unique string that identifies this resource + 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(method='DELETE', uri=self._uri, ) - def fetch(self): - """ - Fetch the MediaInstance +class MediaPage(Page): - :returns: The fetched MediaInstance - :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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.get('account_sid'), - 'content_type': payload.get('content_type'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'parent_sid': payload.get('parent_sid'), - 'sid': payload.get('sid'), - 'uri': payload.get('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 SID of the Account that created this resource - :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 RFC 2822 date and time in GMT that 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 RFC 2822 date and time in GMT that 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 SID 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: The unique string that identifies this resource - :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 of this resource, relative to `https://api.twilio.com` - :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 the MediaInstance + Constructs a MediaContext - :returns: The 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 d60cc5577b..ba811ec14f 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -1,172 +1,144 @@ -# coding=utf-8 r""" -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 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. + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - :returns: twilio.rest.api.v2010.account.new_key.NewKeyList - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList - """ - super(NewKeyList, self).__init__(version) + Twilio - Api + This is the public Twilio REST API. - # 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 the NewKeyInstance + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - :param unicode friendly_name: A string to describe the resource +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values - :returns: The created NewKeyInstance - :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance - """ - data = values.of({'FriendlyName': friendly_name, }) +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return NewKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) +class NewKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + 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.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'secret': payload.get('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 unique string that identifies the resource - :rtype: unicode + :returns: The created NewKeyInstance """ - return self._properties['sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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 RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def secret(self): - """ - :returns: The secret your application uses to sign Access Tokens and to authenticate to the REST API. - :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 3c438e4b9c..95341d31cb 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -1,172 +1,144 @@ -# coding=utf-8 r""" -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 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. + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - :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) + Twilio - Api + This is the public Twilio REST API. - # 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 the NewSigningKeyInstance + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - :param unicode friendly_name: A string to describe the resource +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values - :returns: The created NewSigningKeyInstance - :rtype: twilio.rest.api.v2010.account.new_signing_key.NewSigningKeyInstance - """ - data = values.of({'FriendlyName': friendly_name, }) +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return NewSigningKeyInstance(self._version, payload, account_sid=self._solution['account_sid'], ) +class NewSigningKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewSigningKey resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + 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.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'secret': payload.get('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 unique string that identifies the resource - :rtype: unicode + :returns: The created NewSigningKeyInstance """ - return self._properties['sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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 RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def secret(self): - """ - :returns: The secret your application uses to sign Access Tokens and to authenticate to the REST API. - :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 fecf3ba24d..cd35efeabf 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -1,479 +1,540 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created 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.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) + return self._proxy.fetch() - 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'], - ) + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance - return self._version.stream(page, limits['limit']) - 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): + :returns: The fetched NotificationInstance """ - Lists NotificationInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param 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) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.notification.NotificationInstance] + def __repr__(self) -> str: """ - 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, - )) + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Retrieve a single page of NotificationInstance 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: 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: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - data = 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, - }) + Initialize the NotificationContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + super().__init__(version) - return NotificationPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Notifications/{sid}.json".format( + **self._solution + ) - def get_page(self, target_url): + def fetch(self) -> NotificationInstance: """ - Retrieve a specific page of NotificationInstance records from the API. - Request is executed immediately + Fetch the NotificationInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage + :returns: The fetched NotificationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return NotificationPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a NotificationContext + headers["Accept"] = "application/json" - :param sid: The unique string that identifies the resource + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :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, ) + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_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 unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.notification.NotificationContext - :rtype: twilio.rest.api.v2010.account.notification.NotificationContext + :returns: The fetched NotificationInstance """ - return NotificationContext(self._version, account_sid=self._solution['account_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 = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) -class NotificationPage(Page): - """ """ + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the NotificationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.notification.NotificationPage - :rtype: twilio.rest.api.v2010.account.notification.NotificationPage + :returns: Machine friendly representation """ - super(NotificationPage, 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 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the 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 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) + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Notifications.json".format( + **self._solution + ) - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched NotificationInstance - :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + :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 __repr__(self): - """ - Provide a friendly representation + return self._version.stream(page, limits["limit"]) - :returns: Machine friendly representation - :rtype: str + 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]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) -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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'call_sid': payload.get('call_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'error_code': payload.get('error_code'), - 'log': payload.get('log'), - 'message_date': deserialize.rfc2822_datetime(payload.get('message_date')), - 'message_text': payload.get('message_text'), - 'more_info': payload.get('more_info'), - 'request_method': payload.get('request_method'), - 'request_url': payload.get('request_url'), - 'request_variables': payload.get('request_variables'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) - # 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 SID of the Account that created the resource - :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 used to generate the notification - :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 SID of the Call the resource is associated with - :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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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): + def get_page(self, target_url: str) -> NotificationPage: """ - :returns: The HTTP body returned by your server - :rtype: unicode - """ - 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 + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance """ - return self._properties['response_headers'] + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def sid(self): + async def get_page_async(self, target_url: str) -> NotificationPage: """ - :returns: The unique string that identifies the 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['sid'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) - @property - def uri(self): + def get(self, sid: str) -> NotificationContext: """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. """ - return self._properties['uri'] + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> NotificationContext: """ - Fetch the NotificationInstance + Constructs a NotificationContext - :returns: The 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 __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 876a80a5f8..eeb9954c75 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -1,422 +1,620 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created 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.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: The phone number of the OutgoingCallerId resources to read - :param unicode friendly_name: The string that identifies the OutgoingCallerId resources to read - :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']) + 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: The phone number of the OutgoingCallerId resources to read - :param unicode friendly_name: The string that identifies the OutgoingCallerId resources to read - :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: The phone number of the OutgoingCallerId resources to read - :param unicode friendly_name: The string that identifies the OutgoingCallerId resources to read - :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 """ - data = values.of({ - 'PhoneNumber': phone_number, - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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: The unique string that identifies the resource + :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: The unique string that identifies the resource + :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 SID of the Account that created the resource + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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({}) + + headers["Accept"] = "application/json" - def fetch(self): + 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 the OutgoingCallerIdInstance + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + :returns: The fetched OutgoingCallerIdInstance - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 string to describe the resource + :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 - :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return OutgoingCallerIdInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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.get('sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'account_sid': payload.get('account_sid'), - 'phone_number': payload.get('phone_number'), - 'uri': payload.get('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: The unique string that identifies the resource - :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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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: The string that you assigned to describe the 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 SID of the Account that created the resource - :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 phone number in E.164 format - :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 of the resource, relative to `https://api.twilio.com` - :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 the OutgoingCallerIdInstance + response = self._version.domain.twilio.request("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) - :returns: The 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 string to describe the resource + def get(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext - :returns: The 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 48d6e6dde2..e76fda1259 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -1,464 +1,687 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created this resource + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 QueuePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - 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 the QueueInstance + Update the QueueInstance - :param unicode friendly_name: A string to describe this resource - :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: The 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(method='POST', uri=self._uri, data=data, ) - - return QueueInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return self._proxy.update( + friendly_name=friendly_name, + max_size=max_size, + ) - 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: The unique string that identifies this resource + :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: The unique string that identifies this resource - - :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 SID of the Account that created this resource + 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 SID of the Account that created the resource(s) to fetch - :param sid: The unique string that identifies this resource - :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" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._members = None + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> QueueInstance: """ - Fetch the QueueInstance + Asynchronous coroutine to fetch the QueueInstance + :returns: The fetched QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 string to describe this resource - :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: The updated QueueInstance - :rtype: twilio.rest.api.v2010.account.queue.QueueInstance """ - data = values.of({'FriendlyName': friendly_name, 'MaxSize': max_size, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return QueueInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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 = { - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'current_size': deserialize.integer(payload.get('current_size')), - 'friendly_name': payload.get('friendly_name'), - 'uri': payload.get('uri'), - 'account_sid': payload.get('account_sid'), - 'average_wait_time': deserialize.integer(payload.get('average_wait_time')), - 'sid': payload.get('sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'max_size': deserialize.integer(payload.get('max_size')), - } - - # 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 date_updated(self): + +class QueueList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime + 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['date_updated'] + super().__init__(version) - @property - def current_size(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: The number of calls currently 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['current_size'] - @property - def friendly_name(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: A string that you assigned to describe this resource - :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['friendly_name'] - @property - def uri(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 URI of this resource, relative to `https://api.twilio.com` - :rtype: unicode + 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['uri'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def account_sid(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 SID of the Account that created this resource - :rtype: unicode + 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['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def average_wait_time(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: """ - :returns: Average wait time of members in the 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['average_wait_time'] + 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[QueueInstance]: """ - :returns: The unique string that identifies this resource - :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['sid'] + 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, + ) -> QueuePage: """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime + 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['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def max_size(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 max number of calls allowed in the queue - :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['max_size'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, self._solution) - def fetch(self): + def get_page(self, target_url: str) -> QueuePage: """ - Fetch the QueueInstance + Retrieve a specific page of QueueInstance records from the API. + Request is executed immediately - :returns: The 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 string to describe this resource - :param unicode max_size: The max number of calls allowed in the queue + :param target_url: API-generated URL for the requested results page - :returns: The 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 a1c38ead25..30ff4abbc7 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -1,398 +1,564 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created this resource - :param queue_sid: The SID of the Queue the member is in + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return MemberPage(self._version, response, self._solution) + return self._proxy.update( + url=url, + method=method, + ) - 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 of the resource(s) to fetch - :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 of the resource(s) to fetch + 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 SID of the Account that created this resource - :param queue_sid: The SID of the Queue the member is in + 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" - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource(s) to fetch - :param queue_sid: The SID of the Queue in which to find the members - :param call_sid: The Call SID of the resource(s) to fetch + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.api.v2010.account.queue.member.MemberContext - :rtype: twilio.rest.api.v2010.account.queue.member.MemberContext + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: """ - 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 the MemberInstance - :returns: The fetched MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return MemberInstance( self._version, payload, - account_sid=self._solution['account_sid'], - queue_sid=self._solution['queue_sid'], - call_sid=self._solution['call_sid'], + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], ) - def update(self, url, method=values.unset): + def __repr__(self) -> str: """ - Update the MemberInstance - - :param unicode url: The absolute URL of the Queue resource - :param unicode method: How to pass the update request data + Provide a friendly representation - :returns: The 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(method='POST', uri=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.get('call_sid'), - 'date_enqueued': deserialize.rfc2822_datetime(payload.get('date_enqueued')), - 'position': deserialize.integer(payload.get('position')), - 'uri': payload.get('uri'), - 'wait_time': deserialize.integer(payload.get('wait_time')), - 'queue_sid': payload.get('queue_sid'), - } + """ + 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: The SID of the Call the resource is associated with - :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 of the resource, relative to `https://api.twilio.com` - :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: """ - :returns: The number of seconds the member has been in the queue. - :rtype: unicode + 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 """ - return self._properties['wait_time'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def queue_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 MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: """ - :returns: The SID of the Queue the member is in - :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['queue_sid'] + 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 the MemberInstance + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :returns: The fetched MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + :param target_url: API-generated URL for the requested results page + + :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=values.unset): + def get(self, call_sid: str) -> MemberContext: """ - Update the MemberInstance + Constructs a MemberContext - :param unicode url: The absolute URL of the Queue resource - :param unicode method: How to pass the update request data + :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: The updated MemberInstance - :rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance + def __call__(self, call_sid: str) -> MemberContext: """ - return self._proxy.update(url, method=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 485b192795..807fb3ca6e 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -1,587 +1,720 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource + 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. - - :param datetime date_created_before: Only include recordings that were created on this date - :param datetime date_created: Only include recordings that were created on this date - :param datetime date_created_after: Only include recordings that were created on this date - :param unicode call_sid: The Call SID of the resources to read - :param unicode conference_sid: Read by unique Conference SID for the recording - :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.RecordingInstance] + :returns: RecordingContext for this RecordingInstance """ - limits = self._version.read_limits(limit, page_size) - - 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']) + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - 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): + def delete(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. + Deletes the RecordingInstance - :param datetime date_created_before: Only include recordings that were created on this date - :param datetime date_created: Only include recordings that were created on this date - :param datetime date_created_after: Only include recordings that were created on this date - :param unicode call_sid: The Call SID of the resources to read - :param unicode conference_sid: Read by unique Conference SID for the recording - :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 self._proxy.delete() - 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): + async def delete_async(self) -> bool: """ - Retrieve a single page of RecordingInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the RecordingInstance - :param datetime date_created_before: Only include recordings that were created on this date - :param datetime date_created: Only include recordings that were created on this date - :param datetime date_created_after: Only include recordings that were created on this date - :param unicode call_sid: The Call SID of the resources to read - :param unicode conference_sid: Read by unique Conference SID for the recording - :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.recording.RecordingPage + :returns: True if delete succeeds, False otherwise """ - data = 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(method='GET', uri=self._uri, params=data, ) + return await self._proxy.delete_async() - return RecordingPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Retrieve a specific page of RecordingInstance records from the API. - Request is executed immediately + 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 self._proxy.fetch( + include_soft_deleted=include_soft_deleted, ) - return RecordingPage(self._version, response, self._solution) - - def get(self, sid): + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": """ - Constructs a RecordingContext + Asynchronous coroutine to fetch the RecordingInstance - :param sid: The unique string that identifies the resource + :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 """ - return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + return await self._proxy.fetch_async( + include_soft_deleted=include_soft_deleted, + ) - def __call__(self, sid): + @property + def add_on_results(self) -> AddOnResultList: """ - Constructs a RecordingContext - - :param sid: The unique string that identifies the resource + Access the add_on_results + """ + return self._proxy.add_on_results - :returns: twilio.rest.api.v2010.account.recording.RecordingContext - :rtype: twilio.rest.api.v2010.account.recording.RecordingContext + @property + def transcriptions(self) -> TranscriptionList: """ - return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Access the transcriptions + """ + 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 SID of the Account that created the resource + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource + :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 the RecordingInstance + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. :returns: The fetched RecordingInstance - :rtype: twilio.rest.api.v2010.account.recording.RecordingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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) + + +class RecordingPage(Page): - def __repr__(self): + 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" - ABSENT = "absent" + 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'call_sid': payload.get('call_sid'), - 'conference_sid': payload.get('conference_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'start_time': deserialize.rfc2822_datetime(payload.get('start_time')), - 'duration': payload.get('duration'), - 'sid': payload.get('sid'), - 'price': payload.get('price'), - 'price_unit': payload.get('price_unit'), - 'status': payload.get('status'), - 'channels': deserialize.integer(payload.get('channels')), - 'source': payload.get('source'), - 'error_code': deserialize.integer(payload.get('error_code')), - 'uri': payload.get('uri'), - 'encryption_details': payload.get('encryption_details'), - 'subresource_uris': payload.get('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 SID of the Account that created the resource - :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 API version used 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 SID of the Call the resource is associated with - :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. - :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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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 start_time(self): - """ - :returns: The start time of the recording, given in RFC 2822 format - :rtype: datetime + :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['start_time'] + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately - @property - def duration(self): - """ - :returns: The length of the recording in seconds. - :rtype: unicode - """ - return self._properties['duration'] + :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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Page of RecordingInstance """ - return self._properties['sid'] + 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(self): - """ - :returns: The one-time cost of creating the recording. - :rtype: unicode - """ - return self._properties['price'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def price_unit(self): - """ - :returns: The currency used in the price property. - :rtype: unicode - """ - return self._properties['price_unit'] + headers["Accept"] = "application/json" - @property - def status(self): - """ - :returns: The status of the recording. - :rtype: RecordingInstance.Status - """ - return self._properties['status'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) - @property - def channels(self): - """ - :returns: The number of channels in the final recording file as an integer. - :rtype: unicode - """ - return self._properties['channels'] + 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 source(self): - """ - :returns: How the recording was created - :rtype: RecordingInstance.Source - """ - return self._properties['source'] + :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 error_code(self): - """ - :returns: More information about why the recording is missing, if status is `absent`. - :rtype: unicode + :returns: Page of RecordingInstance """ - return self._properties['error_code'] + 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 uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def encryption_details(self): - """ - :returns: How to decrypt the recording. - :rtype: dict - """ - return self._properties['encryption_details'] + headers["Accept"] = "application/json" - @property - def subresource_uris(self): - """ - :returns: A list of related resources identified by their relative URIs - :rtype: unicode - """ - return self._properties['subresource_uris'] + 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 the RecordingInstance + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately - :returns: The 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 27cb52d894..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,459 +1,553 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :param reference_sid: The SID of the recording to which the AddOnResult resource belongs + 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']) + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AddOnResultPage(self._version, response, self._solution) + return await self._proxy.delete_async() - 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: The unique string that identifies the resource to fetch - :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: The unique string that identifies the resource to fetch - - :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 SID of the Account that created the resource - :param reference_sid: The SID of the recording to which the AddOnResult resource belongs + 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 SID of the Account that created the resource to fetch - :param reference_sid: The SID of the recording to which the result to fetch belongs - :param sid: The unique string that identifies the resource to fetch - :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 the AddOnResultInstance + :returns: The fetched AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'status': payload.get('status'), - 'add_on_sid': payload.get('add_on_sid'), - 'add_on_configuration_sid': payload.get('add_on_configuration_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'date_completed': deserialize.rfc2822_datetime(payload.get('date_completed')), - 'reference_sid': payload.get('reference_sid'), - 'subresource_uris': payload.get('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: The unique string that identifies the resource - :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 SID of the Account that created the resource - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def status(self): - """ - :returns: The status of the 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: The SID of the Add-on to which the result belongs - :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: The SID of 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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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 and time in GMT that the 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: The SID of the recording to which the AddOnResult resource belongs - :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: A list of related resources identified by their relative 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 the AddOnResultInstance + Asynchronously retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately - :returns: The fetched AddOnResultInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance + :param target_url: API-generated URL for the requested results page + + :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 86647c8ded..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,446 +1,566 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload belongs - :param add_on_result_sid: The SID of the AddOnResult to which the payload belongs + :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. - - :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.recording.add_on_result.payload.PayloadInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the PayloadInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + 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 self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "PayloadInstance": """ - Retrieve a single page of PayloadInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the PayloadInstance - :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 PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage + :returns: The fetched PayloadInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + @property + def data(self) -> DataList: + """ + Access the data + """ + return self._proxy.data - return PayloadPage(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 PayloadInstance 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 PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadPage +class PayloadContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: str, + ): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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(self, sid): + def delete(self) -> bool: """ - Constructs a PayloadContext + Deletes the PayloadInstance - :param sid: The unique string that identifies the resource to fetch - :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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def __call__(self, sid): + def fetch(self) -> PayloadInstance: """ - Constructs a PayloadContext + Fetch the PayloadInstance - :param sid: The unique string that identifies the resource to fetch - :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" - def __init__(self, version, response, solution): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + + @property + def data(self) -> DataList: """ - Initialize the PayloadPage + Access the data + """ + if self._data is None: + self._data = DataList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["add_on_result_sid"], + self._solution["sid"], + ) + return self._data - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload belongs - :param add_on_result_sid: The SID of the AddOnResult to which the payload belongs + 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 SID of the Account that created the 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 unique string that identifies the resource to fetch + :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 the 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: The fetched PayloadInstance - :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=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.get('sid'), - 'add_on_result_sid': payload.get('add_on_result_sid'), - 'account_sid': payload.get('account_sid'), - 'label': payload.get('label'), - 'add_on_sid': payload.get('add_on_sid'), - 'add_on_configuration_sid': payload.get('add_on_configuration_sid'), - 'content_type': payload.get('content_type'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'reference_sid': payload.get('reference_sid'), - 'subresource_uris': payload.get('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): + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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: The SID of the AddOnResult to which the payload belongs - :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 SID of the Account that created the resource - :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: The 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: The SID of the Add-on to which the result belongs - :rtype: unicode - """ - return self._properties['add_on_sid'] + headers["Accept"] = "application/json" - @property - def add_on_configuration_sid(self): - """ - :returns: The SID of 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): + async def 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: """ - :returns: The MIME type of the payload - :rtype: unicode - """ - 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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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: The SID of the recording to which the AddOnResult resource that contains the payload belongs - :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: A list of related resources identified by their relative 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 the PayloadInstance + Constructs a PayloadContext - :returns: The 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 6102184d6f..472f5b2bff 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -1,450 +1,524 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource - :param recording_sid: The SID that identifies the transcription's recording + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 unique string that identifies the resource + 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 unique string that identifies the resource - :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 SID of the Account that created the resource - :param recording_sid: The SID that identifies the transcription's recording - :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 SID of the Account that created the resource to fetch - :param recording_sid: The SID of the recording that created the transcriptions to fetch - :param sid: The unique string that identifies the resource + 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 the TranscriptionInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'duration': payload.get('duration'), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'recording_sid': payload.get('recording_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'transcription_text': payload.get('transcription_text'), - 'type': payload.get('type'), - 'uri': payload.get('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. - # Context - self._context = None + """ + super().__init__(version) + + # 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 SID of the Account that created the resource - :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 used to create the transcription - :rtype: unicode - """ - return self._properties['api_version'] + return self._version.stream(page, limits["limit"]) - @property - def date_created(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - 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 RFC 2822 date and time in GMT that the resource was last 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 of the transcribed audio in seconds. - :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 charge for the transcription - :rtype: unicode - """ - return self._properties['price'] + return self._version.stream_async(page, limits["limit"]) - @property - def price_unit(self): - """ - :returns: The currency in which price is measured - :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 SID that identifies the transcription's recording - :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 unique string that identifies the resource - :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 transcription 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 of the resource, relative to `https://api.twilio.com` - :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 the TranscriptionInstance + Constructs a TranscriptionContext - :returns: The 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 99b7a46957..eae35c4aa5 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -1,473 +1,650 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created this 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.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: The string that identifies the ShortCode resources to read - :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']) + 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: The string that identifies the ShortCode resources to read - :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] - """ - return list(self.stream( - friendly_name=friendly_name, - short_code=short_code, - limit=limit, - page_size=page_size, - )) - def page(self, friendly_name=values.unset, short_code=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: The fetched ShortCodeInstance """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately + return await self._proxy.fetch_async() - :param unicode friendly_name: The string that identifies the ShortCode resources to read - :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 - - :returns: Page of ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage + 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": """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ShortCode': short_code, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + Update the ShortCodeInstance - return ShortCodePage(self._version, response, self._solution) + :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`. - def get_page(self, target_url): + :returns: The updated ShortCodeInstance """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: 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): + def __repr__(self) -> str: """ - Constructs a ShortCodeContext - - :param sid: The unique string that identifies this resource + Provide a friendly representation - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + :returns: Machine friendly representation """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __call__(self, sid): - """ - Constructs a ShortCodeContext - :param sid: The unique string that identifies this resource +class ShortCodeContext(InstanceContext): - :returns: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + def __init__(self, version: Version, account_sid: str, sid: str): """ - return ShortCodeContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Initialize the ShortCodeContext - def __repr__(self): + :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 """ - Provide a friendly representation + super().__init__(version) - :returns: Machine friendly representation - :rtype: str - """ - return '' + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json".format( + **self._solution + ) + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance -class ShortCodePage(Page): - """ """ - def __init__(self, version, response, solution): + :returns: The fetched ShortCodeInstance """ - Initialize the ShortCodePage - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created this resource + headers = values.of({}) - :returns: twilio.rest.api.v2010.account.short_code.ShortCodePage - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodePage - """ - super(ShortCodePage, self).__init__(version, response) + headers["Accept"] = "application/json" - # Path Solution - self._solution = solution + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def get_instance(self, payload): + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: """ - Build an instance of ShortCodeInstance + Asynchronous coroutine to 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 = await self._version.fetch_async( + 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): + 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: """ - Initialize the ShortCodeContext + Update the ShortCodeInstance - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource(s) to fetch - :param sid: The unique string that identifies this resource + :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: twilio.rest.api.v2010.account.short_code.ShortCodeContext - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext + :returns: The updated 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) + 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({}) - def fetch(self): - """ - Fetch the ShortCodeInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.api.v2010.account.short_code.ShortCodeInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ShortCodeInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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): - """ - Update the ShortCodeInstance - - :param unicode friendly_name: A string to describe this resource - :param unicode api_version: The API version to use to start a new TwiML session - :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 + 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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'short_code': payload.get('short_code'), - 'sid': payload.get('sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'uri': payload.get('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 SID of the Account that created 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 used to start a new TwiML session - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['api_version'] + return "" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] +class ShortCodeList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, account_sid: str): """ - :returns: A string that you assigned to describe this resource - :rtype: unicode - """ - 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: The unique string that identifies this resource - :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 we use to call the 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 we call when receiving an incoming SMS message to this short code - :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 of this resource, relative to `https://api.twilio.com` - :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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance """ - Fetch the ShortCodeInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - :returns: The 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 string to describe this resource - :param unicode api_version: The API version to use to start a new TwiML session - :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: The 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 2792a93855..8e33f218f5 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -1,371 +1,572 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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" - def fetch(self): + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SigningKeyInstance: """ - Fetch the SigningKeyInstance + Asynchronous coroutine to fetch the SigningKeyInstance + :returns: The fetched SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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: The updated SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return SigningKeyInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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 get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: + """ + Build an instance of SigningKeyInstance + + :param payload: Payload response from the API + """ + return SigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation - def __init__(self, version, payload, account_sid, sid=None): + :returns: Machine friendly representation """ - Initialize the SigningKeyInstance + return "" + + +class SigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the SigningKeyList + + :param version: Version that contains the resource + :param account_sid: - :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance """ - super(SigningKeyInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), + # 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: """ - :returns: The date_created - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The date_updated - :rtype: datetime + Asynchronously retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningKeyInstance """ - return self._properties['date_updated'] + data = values.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 SigningKeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SigningKeyPage: """ - Fetch the SigningKeyInstance + Retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately - :returns: The fetched SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) - def update(self, friendly_name=values.unset): + async def get_page_async(self, target_url: str) -> SigningKeyPage: """ - Update the SigningKeyInstance + Asynchronously retrieve a specific page of SigningKeyInstance 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: The updated SigningKeyInstance - :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance + :returns: Page of SigningKeyInstance """ - return self._proxy.update(friendly_name=friendly_name, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) - def delete(self): + def get(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 __call__(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + 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 6352c46e79..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 10443a9042..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,443 +1,653 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the CredentialListInstance + Update the CredentialListInstance - :param unicode friendly_name: Human readable descriptive text + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: The 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(method='POST', uri=self._uri, data=data, ) - - return CredentialListInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + return self._proxy.update( + friendly_name=friendly_name, + ) - 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 list 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 list 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 + ) + + self._credentials: Optional[CredentialList] = None - def get_instance(self, payload): + 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 unique id of the Account that is responsible for this resource. - :param sid: Fetch by unique credential list 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" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._credentials = None + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> CredentialListInstance: """ - Fetch the CredentialListInstance + Asynchronous coroutine to fetch the CredentialListInstance + :returns: The fetched CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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: Human readable descriptive text + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. :returns: The updated CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return CredentialListInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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 get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: + """ + Build an instance of CredentialListInstance - def __init__(self, version, payload, account_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the CredentialListInstance + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + def __repr__(self) -> str: """ - super(CredentialListInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - } + :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: Human readable descriptive text - :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 list of credentials associated with this credential list. - :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: """ - :returns: The URI for this resource - :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['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 = 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: """ - Fetch the CredentialListInstance + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately - :returns: The fetched CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :param page_token: PageToken provided by the API + :param page_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._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 CredentialListPage(self._version, response, self._solution) - def update(self, friendly_name): + def get_page(self, target_url: str) -> CredentialListPage: """ - Update the CredentialListInstance + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately - :param unicode friendly_name: Human readable descriptive text + :param target_url: API-generated URL for the requested results page - :returns: The updated CredentialListInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance + :returns: Page of CredentialListInstance """ - return self._proxy.update(friendly_name, ) + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> CredentialListPage: """ - Deletes the CredentialListInstance + Asynchronously retrieve a specific page of CredentialListInstance 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 CredentialListInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) - @property - def credentials(self): + def get(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 __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The credential list Sid that uniquely identifies this resource + """ + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + 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 4f804a1e84..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,449 +1,666 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 + :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']) - 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + password=password, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def update_async( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance - return CredentialPage(self._version, response, self._solution) + :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`) - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return await self._proxy.update_async( + password=password, + ) - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + :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, 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 the CredentialInstance - :param unicode username: The username for this credential. - :param unicode password: The password will not be returned in the response. + headers = values.of({}) - :returns: The created CredentialInstance - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance + 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 """ - data = values.of({'Username': username, 'Password': password, }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 unique id that identifies the resource to fetch. - :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 unique id that identifies the resource to fetch. + :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" - :param Version version: Version that contains the resource - :param Response response: Response from the API - :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 + 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"], + ) - :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage - :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialPage + def __repr__(self) -> str: """ - super(CredentialPage, 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 CredentialPage(Page): - def get_instance(self, payload): + 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 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 credential - :param sid: The unique id that identifies the resource to fetch. + :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 the CredentialInstance + Create the CredentialInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 will not be returned in the response + :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 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(method='POST', uri=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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'credential_list_sid': payload.get('credential_list_sid'), - 'username': payload.get('username'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'uri': payload.get('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): + 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: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - 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 unique id of the Account that is responsible for this resource. - :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 unique id that identifies the credential list that includes this credential - :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 for this credential. - :rtype: unicode - """ - return self._properties['username'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_created(self): - """ - :returns: The date that this resource was created, given as GMT in RFC 2822 format. - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 format. - :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 for this resource, relative to https://api.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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance """ - Fetch the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response, self._solution) - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - def update(self, password=values.unset): + :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 will not be returned in the response + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 edcc8a7c8e..0a45e68273 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -1,722 +1,977 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.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 - +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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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() + + 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 str target_url: API-generated URL for the requested results page + :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: Page of DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage + :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) + 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. - def create(self, domain_name, friendly_name=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, - emergency_calling_enabled=values.unset, secure=values.unset, - byoc_trunk_sid=values.unset, emergency_caller_sid=values.unset): + :returns: The updated DomainInstance """ - Create the DomainInstance - - :param unicode domain_name: The unique address on Twilio to route SIP traffic - :param unicode friendly_name: A string to describe the resource - :param unicode voice_url: The URL we should call when receiving a call - :param unicode voice_method: The HTTP method to use with voice_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_fallback_method: The HTTP method to use with voice_fallback_url - :param unicode voice_status_callback_url: The URL that we should call to pass status updates - :param unicode voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url` - :param bool sip_registration: Whether SIP registration is allowed - :param bool emergency_calling_enabled: Whether emergency calling is enabled for the domain. - :param bool secure: Whether secure SIP is enabled for the domain - :param unicode byoc_trunk_sid: The SID of the BYOC Trunk resource. - :param unicode emergency_caller_sid: Whether an emergency caller sid is configured for the domain. + 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, + ) - :returns: The created DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.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': sip_registration, - 'EmergencyCallingEnabled': emergency_calling_enabled, - 'Secure': secure, - 'ByocTrunkSid': byoc_trunk_sid, - 'EmergencyCallerSid': emergency_caller_sid, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - 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: The unique string that identifies the resource - - :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: The unique string that identifies the resource + 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: + """ + Access the ip_access_control_list_mappings """ - return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + 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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :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" - # Dependents - self._ip_access_control_list_mappings = None - self._credential_list_mappings = None - self._auth = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DomainInstance: """ - Fetch the DomainInstance + Asynchronous coroutine to fetch the DomainInstance + :returns: The fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, 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, domain_name=values.unset, - emergency_calling_enabled=values.unset, secure=values.unset, - byoc_trunk_sid=values.unset, emergency_caller_sid=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 friendly_name: A string to describe the resource - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_method: The HTTP method we should use with voice_url - :param unicode voice_status_callback_method: The HTTP method we should use to call voice_status_callback_url - :param unicode voice_status_callback_url: The URL that we should call to pass status updates - :param unicode voice_url: The URL we should call when receiving a call - :param bool sip_registration: Whether SIP registration is allowed - :param unicode domain_name: The unique address on Twilio to route SIP traffic - :param bool emergency_calling_enabled: Whether emergency calling is enabled for the domain. - :param bool secure: Whether secure SIP is enabled for the domain - :param unicode byoc_trunk_sid: The SID of the BYOC Trunk resource. - :param unicode emergency_caller_sid: Whether an emergency caller sid is configured for the domain. + :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 - :rtype: twilio.rest.api.v2010.account.sip.domain.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': sip_registration, - 'DomainName': domain_name, - 'EmergencyCallingEnabled': emergency_calling_enabled, - 'Secure': secure, - 'ByocTrunkSid': byoc_trunk_sid, - 'EmergencyCallerSid': emergency_caller_sid, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return DomainInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated DomainInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) @property - def 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 @property - def auth(self): + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: """ - Access the auth - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList + Access the ip_access_control_list_mappings """ - if self._auth is None: - self._auth = AuthTypesList( + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = IpAccessControlListMappingList( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['sid'], + self._solution["account_sid"], + self._solution["sid"], ) - return self._auth + return self._ip_access_control_list_mappings - 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 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'auth_type': payload.get('auth_type'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'domain_name': payload.get('domain_name'), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_status_callback_method': payload.get('voice_status_callback_method'), - 'voice_status_callback_url': payload.get('voice_status_callback_url'), - 'voice_url': payload.get('voice_url'), - 'subresource_uris': payload.get('subresource_uris'), - 'sip_registration': payload.get('sip_registration'), - 'emergency_calling_enabled': payload.get('emergency_calling_enabled'), - 'secure': payload.get('secure'), - 'byoc_trunk_sid': payload.get('byoc_trunk_sid'), - 'emergency_caller_sid': payload.get('emergency_caller_sid'), - } - # 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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def api_version(self): - """ - :returns: The API version used to process the call - :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 RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class DomainList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the 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: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + super().__init__(version) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + # 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: """ - return self._properties['sid'] + Create the DomainInstance - @property - def uri(self): - """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode - """ - return self._properties['uri'] + :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. - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode + :returns: The created DomainInstance """ - return self._properties['voice_fallback_method'] - @property - def voice_fallback_url(self): - """ - :returns: The URL we call when an error occurs while executing TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + 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 voice_method(self): - """ - :returns: The HTTP method to use with voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def voice_status_callback_method(self): - """ - :returns: The HTTP method we use to call voice_status_callback_url - :rtype: unicode - """ - return self._properties['voice_status_callback_method'] + headers["Accept"] = "application/json" - @property - def voice_status_callback_url(self): - """ - :returns: The URL that we call with status updates - :rtype: unicode - """ - return self._properties['voice_status_callback_url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def voice_url(self): - """ - :returns: The URL we call when receiving a call - :rtype: unicode - """ - return self._properties['voice_url'] + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - @property - def subresource_uris(self): - """ - :returns: A list mapping resources associated with the SIP Domain resource - :rtype: unicode - """ - return self._properties['subresource_uris'] + 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. - @property - def sip_registration(self): - """ - :returns: Whether SIP registration is allowed - :rtype: bool + :returns: The created DomainInstance """ - return self._properties['sip_registration'] - @property - def emergency_calling_enabled(self): + 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: Whether emergency calling is enabled for the domain. - :rtype: bool + 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['emergency_calling_enabled'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def secure(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: Whether secure SIP is enabled for the domain - :rtype: bool + 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['secure'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def byoc_trunk_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: """ - :returns: The SID of the BYOC Trunk resource. - :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['byoc_trunk_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def emergency_caller_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: """ - :returns: Whether an emergency caller sid is configured for the domain. - :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['emergency_caller_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def fetch(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: """ - Fetch the DomainInstance + Retrieve a single page of DomainInstance records from the API. + Request is executed immediately - :returns: The fetched DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :param page_token: PageToken provided by the API + :param page_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._proxy.fetch() + 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, 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, domain_name=values.unset, - emergency_calling_enabled=values.unset, secure=values.unset, - byoc_trunk_sid=values.unset, emergency_caller_sid=values.unset): + 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: """ - Update the DomainInstance + Asynchronously retrieve a single page of DomainInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_method: The HTTP method we should use with voice_url - :param unicode voice_status_callback_method: The HTTP method we should use to call voice_status_callback_url - :param unicode voice_status_callback_url: The URL that we should call to pass status updates - :param unicode voice_url: The URL we should call when receiving a call - :param bool sip_registration: Whether SIP registration is allowed - :param unicode domain_name: The unique address on Twilio to route SIP traffic - :param bool emergency_calling_enabled: Whether emergency calling is enabled for the domain. - :param bool secure: Whether secure SIP is enabled for the domain - :param unicode byoc_trunk_sid: The SID of the BYOC Trunk resource. - :param unicode emergency_caller_sid: Whether an emergency caller sid is configured for the domain. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The updated DomainInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance + :returns: Page of DomainInstance """ - return self._proxy.update( - friendly_name=friendly_name, - voice_fallback_method=voice_fallback_method, - voice_fallback_url=voice_fallback_url, - voice_method=voice_method, - voice_status_callback_method=voice_status_callback_method, - voice_status_callback_url=voice_status_callback_url, - voice_url=voice_url, - sip_registration=sip_registration, - domain_name=domain_name, - emergency_calling_enabled=emergency_calling_enabled, - secure=secure, - byoc_trunk_sid=byoc_trunk_sid, - emergency_caller_sid=emergency_caller_sid, + 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 DomainPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DomainPage: """ - Deletes the DomainInstance + 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 = self._version.domain.twilio.request("GET", target_url) + return DomainPage(self._version, response, self._solution) - @property - def ip_access_control_list_mappings(self): + async def get_page_async(self, target_url: str) -> DomainPage: """ - Access the ip_access_control_list_mappings + Asynchronously retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - :returns: 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 + :returns: Page of DomainInstance """ - return self._proxy.ip_access_control_list_mappings + response = await self._version.domain.twilio.request_async("GET", target_url) + return DomainPage(self._version, response, self._solution) - @property - def credential_list_mappings(self): + def get(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 + ) - @property - def auth(self): + def __call__(self, sid: str) -> DomainContext: """ - Access the auth + Constructs a DomainContext - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. """ - return self._proxy.auth + 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 index c80bba1419..73a81ac90d 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py @@ -1,150 +1,86 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping import AuthTypeCallsList -from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping import AuthTypeRegistrationsList +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, account_sid, domain_sid): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthTypesList - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the 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 CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList """ - super(AuthTypesList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'account_sid': account_sid, 'domain_sid': domain_sid, } + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth.json".format( + **self._solution + ) - # Components - self._calls = None - self._registrations = None + self._calls: Optional[AuthTypeCallsList] = None + self._registrations: Optional[AuthTypeRegistrationsList] = None @property - def calls(self): + def calls(self) -> AuthTypeCallsList: """ Access the calls - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList """ if self._calls is None: self._calls = AuthTypeCallsList( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) return self._calls @property - def registrations(self): + def registrations(self) -> AuthTypeRegistrationsList: """ Access the registrations - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList """ if self._registrations is None: self._registrations = AuthTypeRegistrationsList( self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], ) return self._registrations - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypesPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthTypesPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesPage - """ - super(AuthTypesPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthTypesInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance - """ - return AuthTypesInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypesInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid): - """ - Initialize the AuthTypesInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance - """ - super(AuthTypesInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'domain_sid': domain_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/domain/auth_types/auth_calls_mapping/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/__init__.py deleted file mode 100644 index 1c81ed4f2e..0000000000 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/__init__.py +++ /dev/null @@ -1,150 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping import AuthCallsCredentialListMappingList -from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping import AuthCallsIpAccessControlListMappingList - - -class AuthTypeCallsList(ListResource): - """ """ - - def __init__(self, version, account_sid, domain_sid): - """ - Initialize the AuthTypeCallsList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList - """ - super(AuthTypeCallsList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'domain_sid': domain_sid, } - - # Components - self._credential_list_mappings = None - self._ip_access_control_list_mappings = None - - @property - def credential_list_mappings(self): - """ - Access the credential_list_mappings - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingList - """ - 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): - """ - Access the ip_access_control_list_mappings - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingList - """ - 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypeCallsPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthTypeCallsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsPage - """ - super(AuthTypeCallsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthTypeCallsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance - """ - return AuthTypeCallsInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypeCallsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid): - """ - Initialize the AuthTypeCallsInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance - """ - super(AuthTypeCallsInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'domain_sid': domain_sid, } - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/auth_calls_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/auth_calls_credential_list_mapping.py deleted file mode 100644 index 4e5d1e33fb..0000000000 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/auth_calls_credential_list_mapping.py +++ /dev/null @@ -1,393 +0,0 @@ -# coding=utf-8 -r""" -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 AuthCallsCredentialListMappingList(ListResource): - """ """ - - def __init__(self, version, account_sid, domain_sid): - """ - Initialize the AuthCallsCredentialListMappingList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingList - """ - super(AuthCallsCredentialListMappingList, self).__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): - """ - Create the AuthCallsCredentialListMappingInstance - - :param unicode credential_list_sid: The SID of the CredentialList resource to map to the SIP domain - - :returns: The created AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - """ - data = values.of({'CredentialListSid': credential_list_sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AuthCallsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def stream(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance] - """ - 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 AuthCallsCredentialListMappingInstance 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 AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AuthCallsCredentialListMappingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AuthCallsCredentialListMappingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AuthCallsCredentialListMappingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a AuthCallsCredentialListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - """ - return AuthCallsCredentialListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a AuthCallsCredentialListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - """ - return AuthCallsCredentialListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthCallsCredentialListMappingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthCallsCredentialListMappingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingPage - """ - super(AuthCallsCredentialListMappingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthCallsCredentialListMappingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - """ - return AuthCallsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthCallsCredentialListMappingContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, domain_sid, sid): - """ - Initialize the AuthCallsCredentialListMappingContext - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param domain_sid: The SID of the SIP domain that contains the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - """ - super(AuthCallsCredentialListMappingContext, self).__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 fetch(self): - """ - Fetch the AuthCallsCredentialListMappingInstance - - :returns: The fetched AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AuthCallsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the AuthCallsCredentialListMappingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 AuthCallsCredentialListMappingInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid, sid=None): - """ - Initialize the AuthCallsCredentialListMappingInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - """ - super(AuthCallsCredentialListMappingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_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: AuthCallsCredentialListMappingContext for this AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - def fetch(self): - """ - Fetch the AuthCallsCredentialListMappingInstance - - :returns: The fetched AuthCallsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the AuthCallsCredentialListMappingInstance - - :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/sip/domain/auth_types/auth_calls_mapping/auth_calls_ip_access_control_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/auth_calls_ip_access_control_list_mapping.py deleted file mode 100644 index 96c4b303b2..0000000000 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_calls_mapping/auth_calls_ip_access_control_list_mapping.py +++ /dev/null @@ -1,393 +0,0 @@ -# coding=utf-8 -r""" -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 AuthCallsIpAccessControlListMappingList(ListResource): - """ """ - - def __init__(self, version, account_sid, domain_sid): - """ - Initialize the AuthCallsIpAccessControlListMappingList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingList - """ - super(AuthCallsIpAccessControlListMappingList, self).__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): - """ - Create the AuthCallsIpAccessControlListMappingInstance - - :param unicode ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain - - :returns: The created AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - """ - data = values.of({'IpAccessControlListSid': ip_access_control_list_sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AuthCallsIpAccessControlListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def stream(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance] - """ - 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 AuthCallsIpAccessControlListMappingInstance 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 AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AuthCallsIpAccessControlListMappingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AuthCallsIpAccessControlListMappingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AuthCallsIpAccessControlListMappingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a AuthCallsIpAccessControlListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - """ - return AuthCallsIpAccessControlListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a AuthCallsIpAccessControlListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - """ - return AuthCallsIpAccessControlListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthCallsIpAccessControlListMappingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthCallsIpAccessControlListMappingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingPage - """ - super(AuthCallsIpAccessControlListMappingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthCallsIpAccessControlListMappingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - """ - return AuthCallsIpAccessControlListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthCallsIpAccessControlListMappingContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, domain_sid, sid): - """ - Initialize the AuthCallsIpAccessControlListMappingContext - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param domain_sid: The SID of the SIP domain that contains the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - """ - super(AuthCallsIpAccessControlListMappingContext, self).__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 fetch(self): - """ - Fetch the AuthCallsIpAccessControlListMappingInstance - - :returns: The fetched AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AuthCallsIpAccessControlListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the AuthCallsIpAccessControlListMappingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 AuthCallsIpAccessControlListMappingInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid, sid=None): - """ - Initialize the AuthCallsIpAccessControlListMappingInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - """ - super(AuthCallsIpAccessControlListMappingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_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: AuthCallsIpAccessControlListMappingContext for this AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - def fetch(self): - """ - Fetch the AuthCallsIpAccessControlListMappingInstance - - :returns: The fetched AuthCallsIpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the AuthCallsIpAccessControlListMappingInstance - - :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/sip/domain/auth_types/auth_registrations_mapping/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/__init__.py deleted file mode 100644 index 6f21855a71..0000000000 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/__init__.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping import AuthRegistrationsCredentialListMappingList - - -class AuthTypeRegistrationsList(ListResource): - """ """ - - def __init__(self, version, account_sid, domain_sid): - """ - Initialize the AuthTypeRegistrationsList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList - """ - super(AuthTypeRegistrationsList, self).__init__(version) - - # Path Solution - self._solution = {'account_sid': account_sid, 'domain_sid': domain_sid, } - - # Components - self._credential_list_mappings = None - - @property - def credential_list_mappings(self): - """ - Access the credential_list_mappings - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingList - """ - 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): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypeRegistrationsPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthTypeRegistrationsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsPage - """ - super(AuthTypeRegistrationsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthTypeRegistrationsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsInstance - """ - return AuthTypeRegistrationsInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthTypeRegistrationsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid): - """ - Initialize the AuthTypeRegistrationsInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsInstance - """ - super(AuthTypeRegistrationsInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'account_sid': account_sid, 'domain_sid': domain_sid, } - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/auth_registrations_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/auth_registrations_credential_list_mapping.py deleted file mode 100644 index eafbb5f907..0000000000 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_registrations_mapping/auth_registrations_credential_list_mapping.py +++ /dev/null @@ -1,393 +0,0 @@ -# coding=utf-8 -r""" -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 AuthRegistrationsCredentialListMappingList(ListResource): - """ """ - - def __init__(self, version, account_sid, domain_sid): - """ - Initialize the AuthRegistrationsCredentialListMappingList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingList - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingList - """ - super(AuthRegistrationsCredentialListMappingList, self).__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): - """ - Create the AuthRegistrationsCredentialListMappingInstance - - :param unicode credential_list_sid: The SID of the CredentialList resource to map to the SIP domain - - :returns: The created AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - """ - data = values.of({'CredentialListSid': credential_list_sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AuthRegistrationsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def stream(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance] - """ - 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 AuthRegistrationsCredentialListMappingInstance 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 AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AuthRegistrationsCredentialListMappingPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of AuthRegistrationsCredentialListMappingInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AuthRegistrationsCredentialListMappingPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a AuthRegistrationsCredentialListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - """ - return AuthRegistrationsCredentialListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a AuthRegistrationsCredentialListMappingContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - """ - return AuthRegistrationsCredentialListMappingContext( - self._version, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthRegistrationsCredentialListMappingPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the AuthRegistrationsCredentialListMappingPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The SID of the Account that created the resource - :param domain_sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingPage - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingPage - """ - super(AuthRegistrationsCredentialListMappingPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AuthRegistrationsCredentialListMappingInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - """ - return AuthRegistrationsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AuthRegistrationsCredentialListMappingContext(InstanceContext): - """ """ - - def __init__(self, version, account_sid, domain_sid, sid): - """ - Initialize the AuthRegistrationsCredentialListMappingContext - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param domain_sid: The SID of the SIP domain that contains the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - """ - super(AuthRegistrationsCredentialListMappingContext, self).__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 fetch(self): - """ - Fetch the AuthRegistrationsCredentialListMappingInstance - - :returns: The fetched AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AuthRegistrationsCredentialListMappingInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - domain_sid=self._solution['domain_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the AuthRegistrationsCredentialListMappingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 AuthRegistrationsCredentialListMappingInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid, domain_sid, sid=None): - """ - Initialize the AuthRegistrationsCredentialListMappingInstance - - :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - """ - super(AuthRegistrationsCredentialListMappingInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - } - - # Context - self._context = None - self._solution = { - 'account_sid': account_sid, - 'domain_sid': domain_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: AuthRegistrationsCredentialListMappingContext for this AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingContext - """ - 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 - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - def fetch(self): - """ - Fetch the AuthRegistrationsCredentialListMappingInstance - - :returns: The fetched AuthRegistrationsCredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the AuthRegistrationsCredentialListMappingInstance - - :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/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 69f55f2466..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,411 +1,568 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - def __init__(self, version, account_sid, domain_sid): + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListMappingContext] = None + + @property + def _proxy(self) -> "CredentialListMappingContext": """ - 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 unique id of the Account that is responsible for this resource. - :param domain_sid: The unique string that identifies the resource + :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 the CredentialListMappingInstance - - :param unicode credential_list_sid: A string that identifies the CredentialList resource to map to the SIP domain + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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. - - :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.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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CredentialListMappingContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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: A string that identifies the resource to fetch - :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: A string that identifies the resource to fetch - :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 unique id of the Account that is responsible for this resource. - :param domain_sid: The unique string that identifies the resource + 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 + + :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 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 unique sid that identifies this account - :param domain_sid: A string that identifies the SIP Domain that includes the resource to fetch - :param sid: A string that identifies the resource to fetch + :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 the CredentialListMappingInstance + Create the CredentialListMappingInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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 + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) - :returns: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.credential_list_mapping.CredentialListMappingInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListMappingInstance]: """ - super(CredentialListMappingInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), - 'subresource_uris': payload.get('subresource_uris'), - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() 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, - 'domain_sid': domain_sid, - 'sid': sid or self._properties['sid'], - } - - @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 unique id of the Account that is responsible for this resource. - :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 that this resource was created, given as GMT in RFC 2822 format. - :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 that this resource was last updated, given as GMT in RFC 2822 format. - :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: A human readable descriptive text for this resource, up to 64 characters long. - :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: A 34 character string that uniquely identifies this resource. - :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 for this resource, relative to https://api.twilio.com - :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 credentials associated with this resource. - :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 the CredentialListMappingInstance + Constructs a CredentialListMappingContext - :returns: The 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 a51fc19b97..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,411 +1,574 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 unique id of the Account that is responsible for this resource. - :param domain_sid: The unique string that identifies the resource + :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 the IpAccessControlListMappingInstance - - :param unicode ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the IpAccessControlListMappingContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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: A 34 character string that uniquely identifies the resource to fetch. - :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: A 34 character string that uniquely identifies the resource to fetch. - :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 unique id of the Account that is responsible for this resource. - :param domain_sid: The unique string that identifies the resource + 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 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 string that uniquely identifies the SIP Domain - :param sid: A 34 character string that uniquely identifies the resource to fetch. + :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 the IpAccessControlListMappingInstance + Create the IpAccessControlListMappingInstance - :returns: The fetched IpAccessControlListMappingInstance - :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingInstance + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'uri': payload.get('uri'), - 'subresource_uris': payload.get('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 unique id of the Account that is responsible for this resource. - :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 that this resource was created, given as GMT in RFC 2822 format. - :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 that this resource was last updated, given as GMT in RFC 2822 format. - :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: A human readable descriptive text for this resource, up to 64 characters long. - :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: A 34 character string that uniquely identifies this resource. - :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 for this resource, relative to https://api.twilio.com - :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 list of IP addresses associated with this domain. - :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 the IpAccessControlListMappingInstance + Constructs a IpAccessControlListMappingContext - :returns: The 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 37e4463fad..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,451 +1,657 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class IpAccessControlListInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + :ivar friendly_name: A human readable descriptive text, up to 255 characters long. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar subresource_uris: A list of the IpAddress resources associated with this IP access control list resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None - def __init__(self, version, account_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 account_sid: A 34 character string that uniquely identifies this resource. + :returns: IpAccessControlListContext for this IpAccessControlListInstance + """ + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListList + def delete(self) -> bool: """ - super(IpAccessControlListList, self).__init__(version) + Deletes the IpAccessControlListInstance - # Path Solution - self._solution = {'account_sid': account_sid, } - self._uri = '/Accounts/{account_sid}/SIP/IpAccessControlLists.json'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the IpAccessControlListInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch 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: The fetched IpAccessControlListInstance """ - 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) -> "IpAccessControlListInstance": """ - Retrieve a single page of IpAccessControlListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Update the IpAccessControlListInstance - return IpAccessControlListPage(self._version, response, self._solution) + :param friendly_name: A human readable descriptive text, up to 255 characters long. - def get_page(self, target_url): + :returns: The updated IpAccessControlListInstance """ - Retrieve a specific page of IpAccessControlListInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + ) - :param str target_url: API-generated URL for the requested results page + async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to update the IpAccessControlListInstance - :returns: Page of IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return IpAccessControlListPage(self._version, response, self._solution) + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses + """ + return self._proxy.ip_addresses - def create(self, friendly_name): + def __repr__(self) -> str: """ - Create the IpAccessControlListInstance + Provide a friendly representation - :param unicode friendly_name: A human readable description of this resource + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The created IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): """ - data = values.of({'FriendlyName': friendly_name, }) + Initialize the IpAccessControlListContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + super().__init__(version) - return IpAccessControlListInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json".format( + **self._solution + ) ) - def get(self, sid): + self._ip_addresses: Optional[IpAddressList] = None + + def delete(self) -> bool: """ - Constructs a IpAccessControlListContext + Deletes the IpAccessControlListInstance - :param sid: A string that identifies the resource to fetch - :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: True if delete succeeds, False otherwise """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) - def __call__(self, sid): - """ - Constructs a IpAccessControlListContext + headers = values.of({}) - :param sid: A string that identifies the resource to fetch + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext + async def delete_async(self) -> bool: """ - return IpAccessControlListContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) + Asynchronous coroutine that deletes the IpAccessControlListInstance - 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 IpAccessControlListPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> IpAccessControlListInstance: """ - Initialize the IpAccessControlListPage + Fetch the IpAccessControlListInstance - :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.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListPage + :returns: The fetched IpAccessControlListInstance """ - super(IpAccessControlListPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of IpAccessControlListInstance + 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.sip.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - """ return IpAccessControlListInstance( 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) -> 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 IpAccessControlListContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, account_sid, sid): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> IpAccessControlListInstance: """ - Initialize the IpAccessControlListContext + Update the IpAccessControlListInstance - :param Version version: Version that contains the resource - :param account_sid: The unique sid that identifies this account - :param sid: A string that identifies the resource to fetch + :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 """ - 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) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) - # Dependents - self._ip_addresses = None + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): - """ - Fetch the IpAccessControlListInstance + headers["Accept"] = "application/json" - :returns: The fetched IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return IpAccessControlListInstance( self._version, payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name): + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: """ - Update the IpAccessControlListInstance + Asynchronous coroutine to 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: The updated IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - def delete(self): - """ - Deletes the IpAccessControlListInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - @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 get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: + """ + Build an instance of IpAccessControlListInstance - def __init__(self, version, payload, account_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the IpAccessControlListInstance + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) - :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + def __repr__(self) -> str: """ - super(IpAccessControlListInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - } + :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]: + """ + 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 """ - :returns: The date this resource 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[IpAccessControlListInstance]: """ - return self._properties['date_created'] + Lists IpAccessControlListInstance 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 resource 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[IpAccessControlListInstance]: """ - return self._properties['date_updated'] + 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. - @property - def subresource_uris(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 IP addresses associated with this resource. - :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, + ) -> IpAccessControlListPage: """ - return self._properties['subresource_uris'] + Retrieve a single page of IpAccessControlListInstance 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 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, + } + ) - 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 IpAccessControlListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListPage: """ - Fetch the IpAccessControlListInstance + Retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately - :returns: The fetched IpAccessControlListInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance + :param target_url: API-generated URL for the requested results page + + :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: The 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 81f936790b..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,489 +1,724 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 unique id of the Account that is responsible for this resource. - :param ip_access_control_list_sid: The unique id of the IpAccessControlList resource that includes this resource. + :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']) - 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 """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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 - return IpAddressPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated IpAddressInstance """ - Retrieve a specific page of IpAddressInstance records from the API. - Request is executed immediately + return await self._proxy.update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressPage + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +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, cidr_prefix_length=values.unset): + + :returns: True if delete succeeds, False otherwise """ - Create the IpAddressInstance - :param unicode friendly_name: A human readable descriptive text for this resource, up to 64 characters long. - :param unicode 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 unicode 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. + headers = values.of({}) - :returns: The created IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAddressInstance: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'IpAddress': ip_address, - 'CidrPrefixLength': cidr_prefix_length, - }) + Fetch the IpAddressInstance + - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :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: A string that identifies the IpAddress resource to fetch - :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: A string that identifies the IpAddress resource to fetch + :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" - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param account_sid: The unique id of the Account that is responsible for this resource. - :param ip_access_control_list_sid: The unique id of the IpAccessControlList resource that includes this resource. + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :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 + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: """ - super(IpAddressPage, 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 IpAddressPage(Page): - def get_instance(self, payload): + 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 unique sid that identifies this account - :param ip_access_control_list_sid: The IpAccessControlList Sid that identifies the IpAddress resources to fetch - :param sid: A string that identifies the IpAddress resource to fetch + :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 the IpAddressInstance + Create the IpAddressInstance - :returns: The fetched IpAddressInstance - :rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, - cidr_prefix_length=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: 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 unicode friendly_name: A human readable descriptive text for this resource, up to 64 characters long. - :param unicode 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. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. - :returns: The 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, - 'CidrPrefixLength': cidr_prefix_length, - }) - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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 + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAddressInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) -class IpAddressInstance(InstanceResource): - """ """ - - 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"]) + + return self._version.stream_async(page, limits["limit"]) - :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 + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'ip_address': payload.get('ip_address'), - 'cidr_prefix_length': deserialize.integer(payload.get('cidr_prefix_length')), - 'ip_access_control_list_sid': payload.get('ip_access_control_list_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'uri': payload.get('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: A 34 character string that uniquely identifies this resource. - :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 unique id of the Account that is responsible for this resource. - :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: A human readable descriptive text for this resource, up to 64 characters long. - :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: 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. - :rtype: unicode - """ - return self._properties['ip_address'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def cidr_prefix_length(self): - """ - :returns: 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. - :rtype: unicode - """ - return self._properties['cidr_prefix_length'] + headers["Accept"] = "application/json" - @property - def ip_access_control_list_sid(self): - """ - :returns: The unique id of the IpAccessControlList resource that includes this resource. - :rtype: unicode - """ - return self._properties['ip_access_control_list_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(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, + ) -> IpAddressPage: """ - :returns: The date that this resource was created, given as GMT in RFC 2822 format. - :rtype: datetime - """ - return self._properties['date_created'] + Asynchronously retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated, given as GMT in RFC 2822 format. - :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 uri(self): + :returns: Page of IpAddressInstance """ - :returns: The URI for this resource, relative to https://api.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 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of IpAddressInstance """ - Fetch the IpAddressInstance + response = self._version.domain.twilio.request("GET", target_url) + return IpAddressPage(self._version, response, self._solution) - :returns: The 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, - cidr_prefix_length=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: 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 unicode friendly_name: A human readable descriptive text for this resource, up to 64 characters long. - :param unicode 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. + def get(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext - :returns: The 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, - cidr_prefix_length=cidr_prefix_length, + 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 25d096e166..fa43360fb1 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -1,190 +1,146 @@ -# coding=utf-8 r""" -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 + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + Twilio - Api + This is the public Twilio REST API. -class TokenList(ListResource): - """ """ - - def __init__(self, version, account_sid): - """ - Initialize the TokenList - - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource - - :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) - - def create(self, ttl=values.unset): - """ - Create the TokenInstance + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - :param unicode ttl: The duration in seconds the credentials are valid +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values - :returns: The created TokenInstance - :rtype: twilio.rest.api.v2010.account.token.TokenInstance - """ - data = values.of({'Ttl': ttl, }) +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], ) +class TokenInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Token resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar ice_servers: An array representing the ephemeral credentials and the STUN and TURN server URIs. + :ivar password: The temporary password that the username will use when authenticating with Twilio. + :ivar ttl: The duration in seconds for which the username and password are valid. + :ivar username: The temporary username that uniquely identifies a Token. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.ice_servers: Optional[List[str]] = payload.get("ice_servers") + self.password: Optional[str] = payload.get("password") + self.ttl: Optional[str] = payload.get("ttl") + self.username: Optional[str] = payload.get("username") + + self._solution = { + "account_sid": account_sid, + } - def __repr__(self): + 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 SID of the Account that created the 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 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.get('account_sid'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'ice_servers': payload.get('ice_servers'), - 'password': payload.get('password'), - 'ttl': payload.get('ttl'), - 'username': payload.get('username'), - } + Asynchronously create the TokenInstance - # Context - self._context = None - self._solution = {'account_sid': account_sid, } - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + :returns: The created TokenInstance """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT that the 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 6297c37078..386ff9ee74 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -1,426 +1,504 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Account that created the resource + """ + :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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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: The unique string that identifies the resource - :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: The unique string that identifies the resource + # 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 SID of the Account that created the resource - :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 + headers = values.of({}) - def get_instance(self, payload): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: """ - Build an instance of TranscriptionInstance + Fetch the TranscriptionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance + :returns: The fetched TranscriptionInstance """ - return TranscriptionInstance(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 TranscriptionContext(InstanceContext): - """ """ + return TranscriptionInstance( + 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) -> TranscriptionInstance: """ - Initialize the TranscriptionContext + Asynchronous coroutine to fetch the TranscriptionInstance - :param Version version: Version that contains the resource - :param account_sid: The SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - :returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext + :returns: The fetched TranscriptionInstance """ - super(TranscriptionContext, self).__init__(version) - # Path Solution - self._solution = {'account_sid': account_sid, 'sid': sid, } - self._uri = '/Accounts/{account_sid}/Transcriptions/{sid}.json'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the TranscriptionInstance + headers["Accept"] = "application/json" - :returns: The fetched TranscriptionInstance - :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __repr__(self): + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance + + :param payload: Payload response from the API + """ + return TranscriptionInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'duration': payload.get('duration'), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'recording_sid': payload.get('recording_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'transcription_text': payload.get('transcription_text'), - 'type': payload.get('type'), - 'uri': payload.get('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 SID of the Account that created the resource - :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 used to create the transcription - :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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that the 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 the 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 SID that identifies the transcription's 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: The unique string that identifies the resource - :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 transcription 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 of the resource, relative to `https://api.twilio.com` - :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 the TranscriptionInstance + Constructs a TranscriptionContext - :returns: The 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 57857f074a..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 2c2179df67..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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,325 +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, include_subaccounts=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: The usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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: The usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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: The usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -349,7 +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" @@ -364,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -424,28 +343,54 @@ 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" - 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" @@ -461,18 +406,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -480,13 +427,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -505,6 +469,7 @@ 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" @@ -515,24 +480,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -541,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" @@ -563,164 +664,653 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["RecordInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account 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 used to create the resource - :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 as_of(self): + :returns: Machine friendly representation """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + return "" + + +class RecordList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - return self._properties['as_of'] + 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 category(self): """ - :returns: The category of usage - :rtype: RecordInstance.Category + 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['category'] + 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(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 number of usage events - :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'] + 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 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 units in which count is measured - :rtype: unicode + 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]: """ - return self._properties['count_unit'] + Lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordInstance]: + """ + Asynchronously lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Asynchronously retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordPage: + """ + Retrieve a specific page of RecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordPage: """ - :returns: A plain-language description of the usage category - :rtype: unicode + 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 """ - return self._properties['description'] + 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 for which usage is included in the UsageRecord - :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 for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative URIs - :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 of the resource, relative to `https://api.twilio.com` - :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 5924bcd023..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,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: AllTimeInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class AllTimePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 558262dab0..e89c75cb39 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -1,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: DailyInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class DailyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 805fb7823e..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,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: LastMonthInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class LastMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 a83a899d7d..117db692bf 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -1,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: MonthlyInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class MonthlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 bc0c792423..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,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: ThisMonthInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class ThisMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 981e2f6e78..393238e76f 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -1,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: TodayInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class TodayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 005008e347..ad9e5a36d8 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -1,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: YearlyInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class YearlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 bdeb6b0e46..f3aacda8b9 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -1,232 +1,125 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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) - - 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']) - - def list(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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, - include_subaccounts=include_subaccounts, - limit=limit, - page_size=page_size, - )) - - def page(self, category=values.unset, start_date=values.unset, - end_date=values.unset, include_subaccounts=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 usage category of the UsageRecord resources to read - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts - :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 - """ - data = values.of({ - 'Category': category, - 'StartDate': serialize.iso8601_date(start_date), - 'EndDate': serialize.iso8601_date(end_date), - 'IncludeSubaccounts': include_subaccounts, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - ) - - 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_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" AUTHY_AUTHENTICATIONS = "authy-authentications" AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" CALL_PROGESS_EVENTS = "call-progess-events" CALLERIDLOOKUPS = "calleridlookups" CALLS = "calls" CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" CALLS_GLOBALCONFERENCE = "calls-globalconference" CALLS_INBOUND = "calls-inbound" CALLS_INBOUND_LOCAL = "calls-inbound-local" CALLS_INBOUND_MOBILE = "calls-inbound-mobile" CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" CALLS_OUTBOUND = "calls-outbound" CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" CALLS_RECORDINGS = "calls-recordings" CALLS_SIP = "calls-sip" CALLS_SIP_INBOUND = "calls-sip-inbound" CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" CONVERSATIONS = "conversations" CONVERSATIONS_API_REQUESTS = "conversations-api-requests" CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" @@ -235,7 +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" @@ -250,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -310,28 +335,54 @@ 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" - 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" @@ -347,18 +398,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -366,13 +419,30 @@ class Category(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -391,6 +461,7 @@ 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" @@ -401,24 +472,146 @@ class Category(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -427,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" @@ -449,164 +656,556 @@ class Category(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'as_of': payload.get('as_of'), - 'category': payload.get('category'), - 'count': payload.get('count'), - 'count_unit': payload.get('count_unit'), - 'description': payload.get('description'), - 'end_date': deserialize.iso8601_date(payload.get('end_date')), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'start_date': deserialize.iso8601_date(payload.get('start_date')), - 'subresource_uris': payload.get('subresource_uris'), - 'uri': payload.get('uri'), - 'usage': payload.get('usage'), - 'usage_unit': payload.get('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 SID of the Account accrued the usage - :rtype: unicode - """ - return self._properties['account_sid'] + self._solution = { + "account_sid": account_sid, + } - @property - def api_version(self): - """ - :returns: The API version used to create the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['api_version'] + Provide a friendly representation - @property - def as_of(self): - """ - :returns: Usage records up to date as of this timestamp - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['as_of'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def category(self): - """ - :returns: The category of usage - :rtype: YesterdayInstance.Category - """ - return self._properties['category'] - @property - def count(self): +class YesterdayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: """ - :returns: The number of usage events - :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 units in which count is measured - :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: A plain-language description of the usage category - :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 last date for which usage is included in the UsageRecord - :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 total price of the usage - :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"], + ) - @property - def price_unit(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: """ - :returns: The currency in which `price` is measured - :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 first date for which usage is included in this UsageRecord - :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: A list of related resources identified by their relative 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 of the resource, relative to `https://api.twilio.com` - :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"}) + + headers["Accept"] = "application/json" - @property - def usage(self): + 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 amount of 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 units in which usage is measured - :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 338d216f4c..7f182a01b3 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -1,359 +1,136 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 the TriggerInstance - - :param unicode callback_url: The URL we call when the trigger fires - :param unicode trigger_value: The usage value at which the trigger should fire - :param TriggerInstance.UsageCategory usage_category: The usage category the trigger watches - :param unicode callback_method: The HTTP method to use to call callback_url - :param unicode friendly_name: A string to describe the resource - :param TriggerInstance.Recurring recurring: The frequency of a recurring UsageTrigger - :param TriggerInstance.TriggerField trigger_by: The field in the UsageRecord resource that fires the trigger - - :returns: The 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(method='POST', uri=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. +class TriggerInstance(InstanceResource): - :param TriggerInstance.Recurring recurring: The frequency of recurring UsageTriggers to read - :param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read - :param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read - :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 Recurring(object): + DAILY = "daily" + MONTHLY = "monthly" + YEARLY = "yearly" + ALLTIME = "alltime" - :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) + class TriggerField(object): + COUNT = "count" + USAGE = "usage" + PRICE = "price" - page = self.page( - recurring=recurring, - trigger_by=trigger_by, - usage_category=usage_category, - page_size=limits['page_size'], + class UsageCategory(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" ) - - return self._version.stream(page, limits['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: The frequency of recurring UsageTriggers to read - :param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read - :param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read - :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: The frequency of recurring UsageTriggers to read - :param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read - :param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read - :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 - """ - data = values.of({ - 'Recurring': recurring, - 'TriggerBy': trigger_by, - 'UsageCategory': usage_category, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" ) - - return TriggerPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a TriggerContext - - :param sid: The unique string that identifies the resource - - :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: The unique string that identifies the resource - - :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 SID of the Account that created the resource to fetch - :param sid: The unique string that identifies the resource - - :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) - - def fetch(self): - """ - Fetch the TriggerInstance - - :returns: The fetched TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TriggerInstance( - self._version, - payload, - account_sid=self._solution['account_sid'], - sid=self._solution['sid'], + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" ) - - def update(self, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): - """ - Update the TriggerInstance - - :param unicode callback_method: The HTTP method to use to call callback_url - :param unicode callback_url: The URL we call when the trigger fires - :param unicode friendly_name: A string to describe the resource - - :returns: The 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(method='POST', uri=self._uri, data=data, ) - - 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(method='DELETE', uri=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" @@ -362,7 +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" @@ -377,56 +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_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = "marketplace-digital-segment-business-info" - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = "marketplace-facebook-offline-conversions" + 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_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_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_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = "marketplace-remeeting-automatic-speech-recognition" - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = "marketplace-tcpa-defense-solutions-blacklist-feed" + 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = "marketplace-voicebase-transcription-custom-vocabulary" - 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_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = "marketplace-ytica-contact-center-reporting-analytics" + 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" @@ -437,28 +346,54 @@ 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" - 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" @@ -474,18 +409,20 @@ 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_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - 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" @@ -493,13 +430,30 @@ class UsageCategory(object): SMS_INBOUND = "sms-inbound" SMS_INBOUND_LONGCODE = "sms-inbound-longcode" SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" SMS_OUTBOUND = "sms-outbound" SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" SPEECH_RECOGNITION = "speech-recognition" STUDIO_ENGAGEMENTS = "studio-engagements" SYNC = "sync" @@ -518,6 +472,7 @@ 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" @@ -528,24 +483,146 @@ class UsageCategory(object): TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" TURNMEGABYTES_USEAST = "turnmegabytes-useast" TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-client-insights-on-demand-minute" - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-ptsn-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-interface-insights-on-demand-minute" - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = "voice-insights-sip-trunking-insights-on-demand-minute" + VOICE_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" @@ -576,238 +667,945 @@ class UsageCategory(object): WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" WIRELESS_USAGE_SMS = "wireless-usage-sms" WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. + :ivar api_version: The API version used to create the resource. + :ivar callback_method: The HTTP method we use to call `callback_url`. Can be: `GET` or `POST`. + :ivar callback_url: The URL we call using the `callback_method` when the trigger fires. + :ivar current_value: The current value of the field the trigger is watching. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_fired: The date and time in GMT that the trigger was last fired specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the trigger. + :ivar recurring: + :ivar sid: The unique string that that we created to identify the UsageTrigger resource. + :ivar trigger_by: + :ivar trigger_value: The value at which the trigger will fire. Must be a positive, numeric value. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage_category: + :ivar usage_record_uri: The URI of the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource this trigger watches, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.callback_method: Optional[str] = payload.get("callback_method") + self.callback_url: Optional[str] = payload.get("callback_url") + self.current_value: Optional[str] = payload.get("current_value") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_fired: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_fired") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.recurring: Optional["TriggerInstance.Recurring"] = payload.get("recurring") + self.sid: Optional[str] = payload.get("sid") + self.trigger_by: Optional["TriggerInstance.TriggerField"] = payload.get( + "trigger_by" + ) + self.trigger_value: Optional[str] = payload.get("trigger_value") + self.uri: Optional[str] = payload.get("uri") + self.usage_category: Optional["TriggerInstance.UsageCategory"] = payload.get( + "usage_category" + ) + self.usage_record_uri: Optional[str] = payload.get("usage_record_uri") - 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.get('account_sid'), - 'api_version': payload.get('api_version'), - 'callback_method': payload.get('callback_method'), - 'callback_url': payload.get('callback_url'), - 'current_value': payload.get('current_value'), - 'date_created': deserialize.rfc2822_datetime(payload.get('date_created')), - 'date_fired': deserialize.rfc2822_datetime(payload.get('date_fired')), - 'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'recurring': payload.get('recurring'), - 'sid': payload.get('sid'), - 'trigger_by': payload.get('trigger_by'), - 'trigger_value': payload.get('trigger_value'), - 'uri': payload.get('uri'), - 'usage_category': payload.get('usage_category'), - 'usage_record_uri': payload.get('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 SID of the Account that 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 used to create the resource - :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: The HTTP method we use to call 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: he URL we call 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 RFC 2822 date and time in GMT that the 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 RFC 2822 date and time in GMT that 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 RFC 2822 date and time in GMT that the 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: The string that you assigned to describe 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: + """ + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise """ - :returns: The frequency of a recurring UsageTrigger - :rtype: TriggerInstance.Recurring + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: """ - return self._properties['recurring'] + Fetch the TriggerInstance - @property - def sid(self): + + :returns: The fetched TriggerInstance """ - :returns: The unique string that identifies the resource - :rtype: unicode + + 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: """ - return self._properties['sid'] + Asynchronous coroutine to fetch the TriggerInstance - @property - def trigger_by(self): + + :returns: The fetched TriggerInstance """ - :returns: The field in the UsageRecord resource that fires the trigger - :rtype: TriggerInstance.TriggerField + + 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: """ - return self._properties['trigger_by'] + Update the TriggerInstance - @property - def trigger_value(self): + :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 """ - :returns: The value at which the trigger will fire - :rtype: unicode + + 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: """ - return self._properties['trigger_value'] + Asynchronous coroutine to update the TriggerInstance - @property - def uri(self): + :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 """ - :returns: The URI of the resource, relative to `https://api.twilio.com` - :rtype: unicode + + 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: """ - return self._properties['uri'] + Provide a friendly representation - @property - def usage_category(self): + :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 + """ + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: """ - :returns: The URI of the UsageRecord resource this trigger watches - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['usage_record_uri'] + return "" + - def fetch(self): +class TriggerList(ListResource): + + def __init__(self, version: Version, account_sid: str): """ - Fetch the TriggerInstance + 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. - :returns: The fetched TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance """ - return self._proxy.fetch() + super().__init__(version) - def update(self, callback_method=values.unset, callback_url=values.unset, - friendly_name=values.unset): + # 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: """ - Update the TriggerInstance + Create the TriggerInstance - :param unicode callback_method: The HTTP method to use to call callback_url - :param unicode callback_url: The URL we call when the trigger fires - :param unicode friendly_name: A string to describe the resource + :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 updated TriggerInstance - :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance + :returns: The created TriggerInstance """ - return self._proxy.update( - callback_method=callback_method, - callback_url=callback_url, - friendly_name=friendly_name, + + 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 ) - def delete(self): + 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 """ - Deletes the TriggerInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + data = values.of( + { + "CallbackUrl": callback_url, + "TriggerValue": trigger_value, + "UsageCategory": usage_category, + "CallbackMethod": callback_method, + "FriendlyName": friendly_name, + "Recurring": recurring, + "TriggerBy": trigger_by, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TriggerInstance]: """ - return self._proxy.delete() + Streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TriggerInstance]: + """ + Asynchronously streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Asynchronously lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + async def page_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Asynchronously retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TriggerPage: + """ + Retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TriggerPage: + """ + Asynchronously retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + def get(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) - def __repr__(self): + 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 6056fcc38a..d92f840e68 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -1,185 +1,173 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. """ +from typing import Any, Dict, Optional, Union from twilio.base import values + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource -from twilio.base.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 SID of the Account that created the resource - - :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 the ValidationRequestInstance +from twilio.base.version import Version - :param unicode phone_number: The phone number to verify in E.164 format - :param unicode friendly_name: A string to describe the resource - :param unicode call_delay: The number of seconds to delay before initiating the verification call - :param unicode extension: The digits to dial after connecting the verification call - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - - :returns: The 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(method='POST', uri=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 SID of the Account that created the resource + :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 + 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: """ - return ValidationRequestInstance(self._version, payload, account_sid=self._solution['account_sid'], ) + Create the ValidationRequestInstance - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: The created ValidationRequestInstance """ - return '' - -class ValidationRequestInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, account_sid): - """ - Initialize the ValidationRequestInstance + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Asynchronously create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. - :returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance - :rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance + :returns: The created ValidationRequestInstance """ - super(ValidationRequestInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'call_sid': payload.get('call_sid'), - 'friendly_name': payload.get('friendly_name'), - 'phone_number': payload.get('phone_number'), - 'validation_code': payload.get('validation_code'), - } - # Context - self._context = None - self._solution = {'account_sid': account_sid, } + 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 account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def call_sid(self): - """ - :returns: The SID of the Call the resource is associated with - :rtype: unicode - """ - return self._properties['call_sid'] + headers["Accept"] = "application/json" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def phone_number(self): - """ - :returns: The phone number to verify in E.164 format - :rtype: unicode - """ - return self._properties['phone_number'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def validation_code(self): - """ - :returns: The 6 digit validation code that someone must enter to validate the Caller ID when `phone_number` is called - :rtype: unicode - """ - return self._properties['validation_code'] + 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/autopilot/__init__.py b/twilio/rest/autopilot/__init__.py deleted file mode 100644 index 1fdb011a8a..0000000000 --- a/twilio/rest/autopilot/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.domain import Domain -from twilio.rest.autopilot.v1 import V1 - - -class Autopilot(Domain): - - def __init__(self, twilio): - """ - Initialize the Autopilot Domain - - :returns: Domain for Autopilot - :rtype: twilio.rest.autopilot.Autopilot - """ - super(Autopilot, self).__init__(twilio) - - self.base_url = 'https://autopilot.twilio.com' - - # Versions - self._v1 = None - - @property - def v1(self): - """ - :returns: Version v1 of autopilot - :rtype: twilio.rest.autopilot.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def assistants(self): - """ - :rtype: twilio.rest.autopilot.v1.assistant.AssistantList - """ - return self.v1.assistants - - @property - def restore_assistant(self): - """ - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantList - """ - return self.v1.restore_assistant - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/autopilot/v1/__init__.py b/twilio/rest/autopilot/v1/__init__.py deleted file mode 100644 index ff9390e4f3..0000000000 --- a/twilio/rest/autopilot/v1/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.autopilot.v1.assistant import AssistantList -from twilio.rest.autopilot.v1.restore_assistant import RestoreAssistantList - - -class V1(Version): - - def __init__(self, domain): - """ - Initialize the V1 version of Autopilot - - :returns: V1 version of Autopilot - :rtype: twilio.rest.autopilot.v1.V1.V1 - """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._assistants = None - self._restore_assistant = None - - @property - def assistants(self): - """ - :rtype: twilio.rest.autopilot.v1.assistant.AssistantList - """ - if self._assistants is None: - self._assistants = AssistantList(self) - return self._assistants - - @property - def restore_assistant(self): - """ - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantList - """ - if self._restore_assistant is None: - self._restore_assistant = RestoreAssistantList(self) - return self._restore_assistant - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/autopilot/v1/assistant/__init__.py b/twilio/rest/autopilot/v1/assistant/__init__.py deleted file mode 100644 index c138219e7c..0000000000 --- a/twilio/rest/autopilot/v1/assistant/__init__.py +++ /dev/null @@ -1,717 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistant.defaults import DefaultsList -from twilio.rest.autopilot.v1.assistant.dialogue import DialogueList -from twilio.rest.autopilot.v1.assistant.field_type import FieldTypeList -from twilio.rest.autopilot.v1.assistant.model_build import ModelBuildList -from twilio.rest.autopilot.v1.assistant.query import QueryList -from twilio.rest.autopilot.v1.assistant.style_sheet import StyleSheetList -from twilio.rest.autopilot.v1.assistant.task import TaskList -from twilio.rest.autopilot.v1.assistant.webhook import WebhookList - - -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.autopilot.v1.assistant.AssistantList - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.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']) - - 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.autopilot.v1.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.autopilot.v1.assistant.AssistantPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.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, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, style_sheet=values.unset, - defaults=values.unset): - """ - Create the AssistantInstance - - :param unicode friendly_name: A string to describe the new resource - :param bool log_queries: Whether queries should be logged and kept after training - :param unicode unique_name: An application-defined string that uniquely identifies the new resource - :param unicode callback_url: Reserved - :param unicode callback_events: Reserved - :param dict style_sheet: A JSON string that defines the Assistant's style sheet - :param dict defaults: A JSON object that defines the Assistant's default tasks for various scenarios - - :returns: The created AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'UniqueName': unique_name, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - 'StyleSheet': serialize.object(style_sheet), - 'Defaults': serialize.object(defaults), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AssistantInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a AssistantContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.AssistantContext - :rtype: twilio.rest.autopilot.v1.assistant.AssistantContext - """ - return AssistantContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a AssistantContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.AssistantContext - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.AssistantPage - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.AssistantInstance - :rtype: twilio.rest.autopilot.v1.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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.AssistantContext - :rtype: twilio.rest.autopilot.v1.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._tasks = None - self._model_builds = None - self._queries = None - self._style_sheet = None - self._defaults = None - self._dialogues = None - self._webhooks = None - - def fetch(self): - """ - Fetch the AssistantInstance - - :returns: The fetched AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AssistantInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, friendly_name=values.unset, log_queries=values.unset, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, style_sheet=values.unset, - defaults=values.unset, development_stage=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: A string to describe the resource - :param bool log_queries: Whether queries should be logged and kept after training - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode callback_url: Reserved - :param unicode callback_events: Reserved - :param dict style_sheet: A JSON string that defines the Assistant's style sheet - :param dict defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios - :param unicode development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'UniqueName': unique_name, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - 'StyleSheet': serialize.object(style_sheet), - 'Defaults': serialize.object(defaults), - 'DevelopmentStage': development_stage, - }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=self._uri, ) - - @property - def field_types(self): - """ - Access the field_types - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList - :rtype: twilio.rest.autopilot.v1.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 tasks(self): - """ - Access the tasks - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskList - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskList - """ - if self._tasks is None: - self._tasks = TaskList(self._version, assistant_sid=self._solution['sid'], ) - return self._tasks - - @property - def model_builds(self): - """ - Access the model_builds - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.query.QueryList - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryList - """ - if self._queries is None: - self._queries = QueryList(self._version, assistant_sid=self._solution['sid'], ) - return self._queries - - @property - def style_sheet(self): - """ - Access the style_sheet - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - """ - if self._style_sheet is None: - self._style_sheet = StyleSheetList(self._version, assistant_sid=self._solution['sid'], ) - return self._style_sheet - - @property - def defaults(self): - """ - Access the defaults - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - """ - if self._defaults is None: - self._defaults = DefaultsList(self._version, assistant_sid=self._solution['sid'], ) - return self._defaults - - @property - def dialogues(self): - """ - Access the dialogues - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - """ - if self._dialogues is None: - self._dialogues = DialogueList(self._version, assistant_sid=self._solution['sid'], ) - return self._dialogues - - @property - def webhooks(self): - """ - Access the webhooks - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - """ - if self._webhooks is None: - self._webhooks = WebhookList(self._version, assistant_sid=self._solution['sid'], ) - return self._webhooks - - 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.autopilot.v1.assistant.AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - super(AssistantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'latest_model_build_sid': payload.get('latest_model_build_sid'), - 'links': payload.get('links'), - 'log_queries': payload.get('log_queries'), - 'development_stage': payload.get('development_stage'), - 'needs_model_build': payload.get('needs_model_build'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - 'callback_url': payload.get('callback_url'), - 'callback_events': payload.get('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.autopilot.v1.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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def latest_model_build_sid(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['latest_model_build_sid'] - - @property - def links(self): - """ - :returns: A list of the URLs of the Assistant's related resources - :rtype: unicode - """ - return self._properties['links'] - - @property - def log_queries(self): - """ - :returns: Whether queries should be logged and kept after training - :rtype: bool - """ - return self._properties['log_queries'] - - @property - def development_stage(self): - """ - :returns: A string describing the state of the assistant. - :rtype: unicode - """ - return self._properties['development_stage'] - - @property - def needs_model_build(self): - """ - :returns: Whether model needs to be rebuilt - :rtype: bool - """ - return self._properties['needs_model_build'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The absolute URL of the Assistant resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def callback_url(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['callback_url'] - - @property - def callback_events(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['callback_events'] - - def fetch(self): - """ - Fetch the AssistantInstance - - :returns: The fetched AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, log_queries=values.unset, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, style_sheet=values.unset, - defaults=values.unset, development_stage=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: A string to describe the resource - :param bool log_queries: Whether queries should be logged and kept after training - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode callback_url: Reserved - :param unicode callback_events: Reserved - :param dict style_sheet: A JSON string that defines the Assistant's style sheet - :param dict defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios - :param unicode development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - :rtype: twilio.rest.autopilot.v1.assistant.AssistantInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - style_sheet=style_sheet, - defaults=defaults, - development_stage=development_stage, - ) - - 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.autopilot.v1.assistant.field_type.FieldTypeList - :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList - """ - return self._proxy.field_types - - @property - def tasks(self): - """ - Access the tasks - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskList - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskList - """ - return self._proxy.tasks - - @property - def model_builds(self): - """ - Access the model_builds - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList - """ - return self._proxy.model_builds - - @property - def queries(self): - """ - Access the queries - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryList - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryList - """ - return self._proxy.queries - - @property - def style_sheet(self): - """ - Access the style_sheet - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - """ - return self._proxy.style_sheet - - @property - def defaults(self): - """ - Access the defaults - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - """ - return self._proxy.defaults - - @property - def dialogues(self): - """ - Access the dialogues - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - """ - return self._proxy.dialogues - - @property - def webhooks(self): - """ - Access the webhooks - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - """ - return self._proxy.webhooks - - 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/autopilot/v1/assistant/defaults.py b/twilio/rest/autopilot/v1/assistant/defaults.py deleted file mode 100644 index 708a71b8ae..0000000000 --- a/twilio/rest/autopilot/v1/assistant/defaults.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 DefaultsList(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 DefaultsList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList - """ - super(DefaultsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a DefaultsContext - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - """ - return DefaultsContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __call__(self): - """ - Constructs a DefaultsContext - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - """ - return DefaultsContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DefaultsPage(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 DefaultsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsPage - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsPage - """ - super(DefaultsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DefaultsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - return DefaultsInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DefaultsContext(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): - """ - Initialize the DefaultsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - """ - super(DefaultsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Defaults'.format(**self._solution) - - def fetch(self): - """ - Fetch the DefaultsInstance - - :returns: The fetched DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DefaultsInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def update(self, defaults=values.unset): - """ - Update the DefaultsInstance - - :param dict defaults: A JSON string that describes the default task links. - - :returns: The updated DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - data = values.of({'Defaults': serialize.object(defaults), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return DefaultsInstance(self._version, payload, assistant_sid=self._solution['assistant_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 DefaultsInstance(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): - """ - Initialize the DefaultsInstance - - :returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - super(DefaultsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_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: DefaultsContext for this DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsContext - """ - if self._context is None: - self._context = DefaultsContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def url(self): - """ - :returns: The absolute URL of the Defaults resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The JSON string that describes the default task links - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the DefaultsInstance - - :returns: The fetched DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - return self._proxy.fetch() - - def update(self, defaults=values.unset): - """ - Update the DefaultsInstance - - :param dict defaults: A JSON string that describes the default task links. - - :returns: The updated DefaultsInstance - :rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsInstance - """ - return self._proxy.update(defaults=defaults, ) - - 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/autopilot/v1/assistant/dialogue.py b/twilio/rest/autopilot/v1/assistant/dialogue.py deleted file mode 100644 index 464ba35d2e..0000000000 --- a/twilio/rest/autopilot/v1/assistant/dialogue.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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 DialogueList(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 DialogueList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList - """ - super(DialogueList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self, sid): - """ - Constructs a DialogueContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - """ - return DialogueContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a DialogueContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - """ - return DialogueContext(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 DialoguePage(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 DialoguePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialoguePage - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialoguePage - """ - super(DialoguePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DialogueInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - """ - return DialogueInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DialogueContext(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 DialogueContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - """ - super(DialogueContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Dialogues/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the DialogueInstance - - :returns: The fetched DialogueInstance - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_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 DialogueInstance(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 DialogueInstance - - :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - """ - super(DialogueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'data': payload.get('data'), - 'url': payload.get('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: DialogueContext for this DialogueInstance - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueContext - """ - if self._context is None: - self._context = DialogueContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def data(self): - """ - :returns: The JSON string that describes the dialogue session object - :rtype: dict - """ - return self._properties['data'] - - @property - def url(self): - """ - :returns: The absolute URL of the Dialogue resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the DialogueInstance - - :returns: The fetched DialogueInstance - :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueInstance - """ - 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/autopilot/v1/assistant/field_type/__init__.py b/twilio/rest/autopilot/v1/assistant/field_type/__init__.py deleted file mode 100644 index b2c57c8a5a..0000000000 --- a/twilio/rest/autopilot/v1/assistant/field_type/__init__.py +++ /dev/null @@ -1,472 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.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']) - - 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.autopilot.v1.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.autopilot.v1.assistant.field_type.FieldTypePage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.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 the FieldTypeInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the new resource - :param unicode friendly_name: A string to describe the new resource - - :returns: The created FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance - """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.autopilot.v1.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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypePage - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.field_type.FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext - :rtype: twilio.rest.autopilot.v1.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 the FieldTypeInstance - - :returns: The fetched FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - - :returns: The updated FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance - """ - data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=self._uri, ) - - @property - def field_values(self): - """ - Access the field_values - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.field_type.FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance - """ - super(FieldTypeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'links': payload.get('links'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('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.autopilot.v1.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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def links(self): - """ - :returns: A list of the URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The absolute URL of the FieldType resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FieldTypeInstance - - :returns: The fetched FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - - :returns: The updated FieldTypeInstance - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.autopilot.v1.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/autopilot/v1/assistant/field_type/field_value.py b/twilio/rest/autopilot/v1/assistant/field_type/field_value.py deleted file mode 100644 index 151d1357dc..0000000000 --- a/twilio/rest/autopilot/v1/assistant/field_type/field_value.py +++ /dev/null @@ -1,456 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Assistant that is the parent of the FieldType associated with the resource - :param field_type_sid: The SID of the Field Type associated with the Field Value - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList - :rtype: twilio.rest.autopilot.v1.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 ISO language-country tag that identifies the language of the value - :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.autopilot.v1.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']) - - 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 ISO language-country tag that identifies the language of the value - :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.autopilot.v1.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 ISO language-country tag that identifies the language of the value - :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.autopilot.v1.assistant.field_type.field_value.FieldValuePage - """ - data = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.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 the FieldValueInstance - - :param unicode language: The ISO language-country tag that identifies the language of the value - :param unicode value: The Field Value data - :param unicode synonym_of: The string value that indicates which word the field value is a synonym of - - :returns: The created FieldValueInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueInstance - """ - data = values.of({'Language': language, 'Value': value, 'SynonymOf': synonym_of, }) - - payload = self._version.create(method='POST', uri=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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.autopilot.v1.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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the FieldType associated with the resource - :param field_type_sid: The SID of the Field Type associated with the Field Value - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValuePage - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.field_type.field_value.FieldValueInstance - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the FieldType associated with the resource to fetch - :param field_type_sid: The SID of the Field Type associated with the Field Value to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueContext - :rtype: twilio.rest.autopilot.v1.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 the FieldValueInstance - - :returns: The fetched FieldValueInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.autopilot.v1.assistant.field_type.field_value.FieldValueInstance - :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueInstance - """ - super(FieldValueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'field_type_sid': payload.get('field_type_sid'), - 'language': payload.get('language'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'value': payload.get('value'), - 'url': payload.get('url'), - 'synonym_of': payload.get('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.autopilot.v1.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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type_sid(self): - """ - :returns: The SID of the Field Type associated with the Field Value - :rtype: unicode - """ - return self._properties['field_type_sid'] - - @property - def language(self): - """ - :returns: The ISO language-country tag that identifies the language of the value - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the FieldType associated with the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def value(self): - """ - :returns: The Field Value data - :rtype: unicode - """ - return self._properties['value'] - - @property - def url(self): - """ - :returns: The absolute URL of the FieldValue resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def synonym_of(self): - """ - :returns: The word for which the field value is a synonym of - :rtype: unicode - """ - return self._properties['synonym_of'] - - def fetch(self): - """ - Fetch the FieldValueInstance - - :returns: The fetched FieldValueInstance - :rtype: twilio.rest.autopilot.v1.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/autopilot/v1/assistant/model_build.py b/twilio/rest/autopilot/v1/assistant/model_build.py deleted file mode 100644 index e37da63355..0000000000 --- a/twilio/rest/autopilot/v1/assistant/model_build.py +++ /dev/null @@ -1,456 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.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']) - - 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.autopilot.v1.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.autopilot.v1.assistant.model_build.ModelBuildPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.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 the ModelBuildInstance - - :param unicode status_callback: The URL we should call using a POST method to send status information to your application - :param unicode unique_name: An application-defined string that uniquely identifies the new resource - - :returns: The created ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance - """ - data = values.of({'StatusCallback': status_callback, 'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.autopilot.v1.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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildPage - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.model_build.ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext - :rtype: twilio.rest.autopilot.v1.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 the ModelBuildInstance - - :returns: The fetched ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: An application-defined string that uniquely identifies the resource - - :returns: The updated ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.autopilot.v1.assistant.model_build.ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance - """ - super(ModelBuildInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - 'build_duration': deserialize.integer(payload.get('build_duration')), - 'error_code': deserialize.integer(payload.get('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.autopilot.v1.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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status of the model build process - :rtype: ModelBuildInstance.Status - """ - return self._properties['status'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The absolute URL of the ModelBuild resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def build_duration(self): - """ - :returns: The time in seconds it took to build the model - :rtype: unicode - """ - return self._properties['build_duration'] - - @property - def error_code(self): - """ - :returns: More information about why the model build failed, if `status` is `failed` - :rtype: unicode - """ - return self._properties['error_code'] - - def fetch(self): - """ - Fetch the ModelBuildInstance - - :returns: The fetched ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance - """ - return self._proxy.fetch() - - def update(self, unique_name=values.unset): - """ - Update the ModelBuildInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - - :returns: The updated ModelBuildInstance - :rtype: twilio.rest.autopilot.v1.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/autopilot/v1/assistant/query.py b/twilio/rest/autopilot/v1/assistant/query.py deleted file mode 100644 index f9b2647044..0000000000 --- a/twilio/rest/autopilot/v1/assistant/query.py +++ /dev/null @@ -1,528 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryList - :rtype: twilio.rest.autopilot.v1.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, dialogue_sid=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 ISO language-country string that specifies the language used by the Query resources to read - :param unicode model_build: The SID or unique name of the Model Build to be queried - :param unicode status: The status of the resources to read - :param unicode dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :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.autopilot.v1.assistant.query.QueryInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit']) - - def list(self, language=values.unset, model_build=values.unset, - status=values.unset, dialogue_sid=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 ISO language-country string that specifies the language used by the Query resources to read - :param unicode model_build: The SID or unique name of the Model Build to be queried - :param unicode status: The status of the resources to read - :param unicode dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :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.autopilot.v1.assistant.query.QueryInstance] - """ - return list(self.stream( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - limit=limit, - page_size=page_size, - )) - - def page(self, language=values.unset, model_build=values.unset, - status=values.unset, dialogue_sid=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 ISO language-country string that specifies the language used by the Query resources to read - :param unicode model_build: The SID or unique name of the Model Build to be queried - :param unicode status: The status of the resources to read - :param unicode dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :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.autopilot.v1.assistant.query.QueryPage - """ - data = values.of({ - 'Language': language, - 'ModelBuild': model_build, - 'Status': status, - 'DialogueSid': dialogue_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.assistant.query.QueryPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return QueryPage(self._version, response, self._solution) - - def create(self, language, query, tasks=values.unset, model_build=values.unset): - """ - Create the QueryInstance - - :param unicode language: The ISO language-country string that specifies the language used for the new query - :param unicode query: The end-user's natural language input - :param unicode tasks: The list of tasks to limit the new query to - :param unicode model_build: The SID or unique name of the Model Build to be queried - - :returns: The created QueryInstance - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryInstance - """ - data = values.of({'Language': language, 'Query': query, 'Tasks': tasks, 'ModelBuild': model_build, }) - - payload = self._version.create(method='POST', uri=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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryContext - :rtype: twilio.rest.autopilot.v1.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 unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryContext - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryPage - :rtype: twilio.rest.autopilot.v1.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.autopilot.v1.assistant.query.QueryInstance - :rtype: twilio.rest.autopilot.v1.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 SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.query.QueryContext - :rtype: twilio.rest.autopilot.v1.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 the QueryInstance - - :returns: The fetched QueryInstance - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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 SID of an optional reference to the Sample created from the query - :param unicode status: The new status of the resource - - :returns: The updated QueryInstance - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryInstance - """ - data = values.of({'SampleSid': sample_sid, 'Status': status, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.autopilot.v1.assistant.query.QueryInstance - :rtype: twilio.rest.autopilot.v1.assistant.query.QueryInstance - """ - super(QueryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'results': payload.get('results'), - 'language': payload.get('language'), - 'model_build_sid': payload.get('model_build_sid'), - 'query': payload.get('query'), - 'sample_sid': payload.get('sample_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'url': payload.get('url'), - 'source_channel': payload.get('source_channel'), - 'dialogue_sid': payload.get('dialogue_sid'), - } - - # 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.autopilot.v1.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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def results(self): - """ - :returns: The natural language analysis results that include the Task recognized and a list of identified Fields - :rtype: dict - """ - return self._properties['results'] - - @property - def language(self): - """ - :returns: The ISO language-country string that specifies the language used by the Query - :rtype: unicode - """ - return self._properties['language'] - - @property - def model_build_sid(self): - """ - :returns: The SID of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) queried - :rtype: unicode - """ - return self._properties['model_build_sid'] - - @property - def query(self): - """ - :returns: The end-user's natural language input - :rtype: unicode - """ - return self._properties['query'] - - @property - def sample_sid(self): - """ - :returns: The SID of an optional reference to the Sample created from the query - :rtype: unicode - """ - return self._properties['sample_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status of the Query - :rtype: unicode - """ - return self._properties['status'] - - @property - def url(self): - """ - :returns: The absolute URL of the Query resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def source_channel(self): - """ - :returns: The communication channel from where the end-user input came - :rtype: unicode - """ - return self._properties['source_channel'] - - @property - def dialogue_sid(self): - """ - :returns: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :rtype: unicode - """ - return self._properties['dialogue_sid'] - - def fetch(self): - """ - Fetch the QueryInstance - - :returns: The fetched QueryInstance - :rtype: twilio.rest.autopilot.v1.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 SID of an optional reference to the Sample created from the query - :param unicode status: The new status of the resource - - :returns: The updated QueryInstance - :rtype: twilio.rest.autopilot.v1.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/autopilot/v1/assistant/style_sheet.py b/twilio/rest/autopilot/v1/assistant/style_sheet.py deleted file mode 100644 index 20f894fd5a..0000000000 --- a/twilio/rest/autopilot/v1/assistant/style_sheet.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 StyleSheetList(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 StyleSheetList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetList - """ - super(StyleSheetList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a StyleSheetContext - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - """ - return StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __call__(self): - """ - Constructs a StyleSheetContext - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - """ - return StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StyleSheetPage(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 StyleSheetPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetPage - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetPage - """ - super(StyleSheetPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of StyleSheetInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StyleSheetContext(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): - """ - Initialize the StyleSheetContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant with the StyleSheet resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - """ - super(StyleSheetContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/StyleSheet'.format(**self._solution) - - def fetch(self): - """ - Fetch the StyleSheetInstance - - :returns: The fetched StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def update(self, style_sheet=values.unset): - """ - Update the StyleSheetInstance - - :param dict style_sheet: The JSON string that describes the style sheet object - - :returns: The updated StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - data = values.of({'StyleSheet': serialize.object(style_sheet), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_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 StyleSheetInstance(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): - """ - Initialize the StyleSheetInstance - - :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - super(StyleSheetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_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: StyleSheetContext for this StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext - """ - if self._context is None: - self._context = StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def url(self): - """ - :returns: The absolute URL of the StyleSheet resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The JSON string that describes the style sheet object - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the StyleSheetInstance - - :returns: The fetched StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - return self._proxy.fetch() - - def update(self, style_sheet=values.unset): - """ - Update the StyleSheetInstance - - :param dict style_sheet: The JSON string that describes the style sheet object - - :returns: The updated StyleSheetInstance - :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance - """ - return self._proxy.update(style_sheet=style_sheet, ) - - 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/autopilot/v1/assistant/task/__init__.py b/twilio/rest/autopilot/v1/assistant/task/__init__.py deleted file mode 100644 index 94dfdedfa7..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/__init__.py +++ /dev/null @@ -1,590 +0,0 @@ -# coding=utf-8 -r""" -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.autopilot.v1.assistant.task.field import FieldList -from twilio.rest.autopilot.v1.assistant.task.sample import SampleList -from twilio.rest.autopilot.v1.assistant.task.task_actions import TaskActionsList -from twilio.rest.autopilot.v1.assistant.task.task_statistics import TaskStatisticsList - - -class TaskList(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 TaskList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskList - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskList - """ - super(TaskList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks'.format(**self._solution) - - def stream(self, 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 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.autopilot.v1.assistant.task.TaskInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.autopilot.v1.assistant.task.TaskInstance] - """ - 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 TaskInstance 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 TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return TaskPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return TaskPage(self._version, response, self._solution) - - def create(self, unique_name, friendly_name=values.unset, actions=values.unset, - actions_url=values.unset): - """ - Create the TaskInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode friendly_name: descriptive string that you create to describe the new resource - :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - :param unicode actions_url: The URL from which the Assistant can fetch actions - - :returns: The created TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'Actions': serialize.object(actions), - 'ActionsUrl': actions_url, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return TaskInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a TaskContext - - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskContext - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskContext - """ - return TaskContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a TaskContext - - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskContext - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskContext - """ - return TaskContext(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 TaskPage(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 TaskPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskPage - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskPage - """ - super(TaskPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - return TaskInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskContext(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 TaskContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskContext - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskContext - """ - super(TaskContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{sid}'.format(**self._solution) - - # Dependents - self._fields = None - self._samples = None - self._task_actions = None - self._statistics = None - - def fetch(self): - """ - Fetch the TaskInstance - - :returns: The fetched TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, friendly_name=values.unset, unique_name=values.unset, - actions=values.unset, actions_url=values.unset): - """ - Update the TaskInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - :param unicode actions_url: The URL from which the Assistant can fetch actions - - :returns: The updated TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Actions': serialize.object(actions), - 'ActionsUrl': actions_url, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the TaskInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - - @property - def fields(self): - """ - Access the fields - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldList - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldList - """ - if self._fields is None: - self._fields = FieldList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - """ - if self._samples is None: - self._samples = SampleList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._samples - - @property - def task_actions(self): - """ - Access the task_actions - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - """ - if self._task_actions is None: - self._task_actions = TaskActionsList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._task_actions - - @property - def statistics(self): - """ - Access the statistics - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - """ - if self._statistics is None: - self._statistics = TaskStatisticsList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._statistics - - 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 TaskInstance(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 TaskInstance - - :returns: twilio.rest.autopilot.v1.assistant.task.TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - super(TaskInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'links': payload.get('links'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'actions_url': payload.get('actions_url'), - 'url': payload.get('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: TaskContext for this TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskContext - """ - if self._context is None: - self._context = TaskContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def links(self): - """ - :returns: A list of the URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def actions_url(self): - """ - :returns: The URL from which the Assistant can fetch actions - :rtype: unicode - """ - return self._properties['actions_url'] - - @property - def url(self): - """ - :returns: The absolute URL of the Task resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the TaskInstance - - :returns: The fetched TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, unique_name=values.unset, - actions=values.unset, actions_url=values.unset): - """ - Update the TaskInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - :param unicode actions_url: The URL from which the Assistant can fetch actions - - :returns: The updated TaskInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - def delete(self): - """ - Deletes the TaskInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete() - - @property - def fields(self): - """ - Access the fields - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldList - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldList - """ - return self._proxy.fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - """ - return self._proxy.samples - - @property - def task_actions(self): - """ - Access the task_actions - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - """ - return self._proxy.task_actions - - @property - def statistics(self): - """ - Access the statistics - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - """ - return self._proxy.statistics - - 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/autopilot/v1/assistant/task/field.py b/twilio/rest/autopilot/v1/assistant/task/field.py deleted file mode 100644 index fa5f086cb1..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/field.py +++ /dev/null @@ -1,438 +0,0 @@ -# coding=utf-8 -r""" -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, task_sid): - """ - Initialize the FieldList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with this Field - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldList - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldList - """ - super(FieldList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_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.autopilot.v1.assistant.task.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']) - - 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.autopilot.v1.assistant.task.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.autopilot.v1.assistant.task.field.FieldPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.assistant.task.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 the FieldInstance - - :param unicode field_type: The Field Type of this field - :param unicode unique_name: An application-defined string that uniquely identifies the new resource - - :returns: The created FieldInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance - """ - data = values.of({'FieldType': field_type, 'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def get(self, sid): - """ - Constructs a FieldContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a FieldContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with this Field - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldPage - :rtype: twilio.rest.autopilot.v1.assistant.task.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.autopilot.v1.assistant.task.field.FieldInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance - """ - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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, task_sid, sid): - """ - Initialize the FieldContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource to fetch - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with the Field resource to fetch - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext - """ - super(FieldContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the FieldInstance - - :returns: The fetched FieldInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FieldInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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, task_sid, sid=None): - """ - Initialize the FieldInstance - - :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance - """ - super(FieldInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'field_type': payload.get('field_type'), - 'task_sid': payload.get('task_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'task_sid': task_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.autopilot.v1.assistant.task.field.FieldContext - """ - if self._context is None: - self._context = FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type(self): - """ - :returns: The Field Type of the field - :rtype: unicode - """ - return self._properties['field_type'] - - @property - def task_sid(self): - """ - :returns: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with this Field - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the Task associated with the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The absolute URL of the Field resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FieldInstance - - :returns: The fetched FieldInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.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/autopilot/v1/assistant/task/sample.py b/twilio/rest/autopilot/v1/assistant/task/sample.py deleted file mode 100644 index 88609e478c..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/sample.py +++ /dev/null @@ -1,494 +0,0 @@ -# coding=utf-8 -r""" -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, task_sid): - """ - Initialize the SampleList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task associated with the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList - """ - super(SampleList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_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 ISO language-country string that specifies the language used for the sample - :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.autopilot.v1.assistant.task.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']) - - 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 ISO language-country string that specifies the language used for the sample - :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.autopilot.v1.assistant.task.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 ISO language-country string that specifies the language used for the sample - :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.autopilot.v1.assistant.task.sample.SamplePage - """ - data = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.autopilot.v1.assistant.task.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 the SampleInstance - - :param unicode language: The ISO language-country string that specifies the language used for the new sample - :param unicode tagged_text: The text example of how end users might express the task - :param unicode source_channel: The communication channel from which the new sample was captured - - :returns: The created SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def get(self, sid): - """ - Constructs a SampleContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a SampleContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task associated with the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SamplePage - :rtype: twilio.rest.autopilot.v1.assistant.task.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.autopilot.v1.assistant.task.sample.SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - """ - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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, task_sid, sid): - """ - Initialize the SampleContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource to fetch - :param task_sid: The SID of the Task associated with the Sample resource to create - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleContext - """ - super(SampleContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the SampleInstance - - :returns: The fetched SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 ISO language-country string that specifies the language used for the sample - :param unicode tagged_text: The text example of how end users might express the task - :param unicode source_channel: The communication channel from which the sample was captured - - :returns: The updated SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SampleInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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, task_sid, sid=None): - """ - Initialize the SampleInstance - - :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance - """ - super(SampleInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'task_sid': payload.get('task_sid'), - 'language': payload.get('language'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'tagged_text': payload.get('tagged_text'), - 'url': payload.get('url'), - 'source_channel': payload.get('source_channel'), - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'task_sid': task_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.autopilot.v1.assistant.task.sample.SampleContext - """ - if self._context is None: - self._context = SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def task_sid(self): - """ - :returns: The SID of the Task associated with the resource - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def language(self): - """ - :returns: An ISO language-country string that specifies the language used for the sample - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the Task associated with the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def tagged_text(self): - """ - :returns: The text example of how end users might express the task - :rtype: unicode - """ - return self._properties['tagged_text'] - - @property - def url(self): - """ - :returns: The absolute URL of the Sample resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def source_channel(self): - """ - :returns: The communication channel from which the sample was captured - :rtype: unicode - """ - return self._properties['source_channel'] - - def fetch(self): - """ - Fetch the SampleInstance - - :returns: The fetched SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.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 ISO language-country string that specifies the language used for the sample - :param unicode tagged_text: The text example of how end users might express the task - :param unicode source_channel: The communication channel from which the sample was captured - - :returns: The updated SampleInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.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/autopilot/v1/assistant/task/task_actions.py b/twilio/rest/autopilot/v1/assistant/task/task_actions.py deleted file mode 100644 index b5aa150618..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/task_actions.py +++ /dev/null @@ -1,303 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 TaskActionsList(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, task_sid): - """ - Initialize the TaskActionsList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task associated with the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsList - """ - super(TaskActionsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - - def get(self): - """ - Constructs a TaskActionsContext - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __call__(self): - """ - Constructs a TaskActionsContext - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskActionsPage(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 TaskActionsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task associated with the resource - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsPage - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsPage - """ - super(TaskActionsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskActionsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskActionsContext(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, task_sid): - """ - Initialize the TaskActionsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task for which the task actions to fetch were defined - :param task_sid: The SID of the Task for which the task actions to fetch were defined - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - """ - super(TaskActionsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Actions'.format(**self._solution) - - def fetch(self): - """ - Fetch the TaskActionsInstance - - :returns: The fetched TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def update(self, actions=values.unset): - """ - Update the TaskActionsInstance - - :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - - :returns: The updated TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - data = values.of({'Actions': serialize.object(actions), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 TaskActionsInstance(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, task_sid): - """ - Initialize the TaskActionsInstance - - :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - super(TaskActionsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'task_sid': payload.get('task_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_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: TaskActionsContext for this TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext - """ - if self._context is None: - self._context = TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the Task associated with the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def task_sid(self): - """ - :returns: The SID of the Task associated with the resource - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def url(self): - """ - :returns: The absolute URL of the TaskActions resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the TaskActionsInstance - - :returns: The fetched TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - return self._proxy.fetch() - - def update(self, actions=values.unset): - """ - Update the TaskActionsInstance - - :param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task - - :returns: The updated TaskActionsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance - """ - return self._proxy.update(actions=actions, ) - - 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/autopilot/v1/assistant/task/task_statistics.py b/twilio/rest/autopilot/v1/assistant/task/task_statistics.py deleted file mode 100644 index 1eafecee75..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/task_statistics.py +++ /dev/null @@ -1,281 +0,0 @@ -# coding=utf-8 -r""" -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 TaskStatisticsList(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, task_sid): - """ - Initialize the TaskStatisticsList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task for which the statistics were collected - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList - """ - super(TaskStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - - def get(self): - """ - Constructs a TaskStatisticsContext - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __call__(self): - """ - Constructs a TaskStatisticsContext - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskStatisticsPage(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 TaskStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the Task associated with the resource - :param task_sid: The SID of the Task for which the statistics were collected - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsPage - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsPage - """ - super(TaskStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskStatisticsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - """ - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskStatisticsContext(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, task_sid): - """ - Initialize the TaskStatisticsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch - :param task_sid: The SID of the Task that is associated with the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - """ - super(TaskStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Statistics'.format(**self._solution) - - def fetch(self): - """ - Fetch the TaskStatisticsInstance - - :returns: The fetched TaskStatisticsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 TaskStatisticsInstance(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, task_sid): - """ - Initialize the TaskStatisticsInstance - - :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - """ - super(TaskStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'task_sid': payload.get('task_sid'), - 'samples_count': deserialize.integer(payload.get('samples_count')), - 'fields_count': deserialize.integer(payload.get('fields_count')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_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: TaskStatisticsContext for this TaskStatisticsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsContext - """ - if self._context is None: - self._context = TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the Task associated with the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def task_sid(self): - """ - :returns: The SID of the Task for which the statistics were collected - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def samples_count(self): - """ - :returns: The total number of Samples associated with the Task - :rtype: unicode - """ - return self._properties['samples_count'] - - @property - def fields_count(self): - """ - :returns: The total number of Fields associated with the Task - :rtype: unicode - """ - return self._properties['fields_count'] - - @property - def url(self): - """ - :returns: The absolute URL of the TaskStatistics resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the TaskStatisticsInstance - - :returns: The fetched TaskStatisticsInstance - :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance - """ - 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/autopilot/v1/assistant/webhook.py b/twilio/rest/autopilot/v1/assistant/webhook.py deleted file mode 100644 index 6b593857fb..0000000000 --- a/twilio/rest/autopilot/v1/assistant/webhook.py +++ /dev/null @@ -1,474 +0,0 @@ -# coding=utf-8 -r""" -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 WebhookList(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 WebhookList - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookList - """ - super(WebhookList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Webhooks'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 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.autopilot.v1.assistant.webhook.WebhookInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.autopilot.v1.assistant.webhook.WebhookInstance] - """ - 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 WebhookInstance 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 WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return WebhookPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return WebhookPage(self._version, response, self._solution) - - def create(self, unique_name, events, webhook_url, webhook_method=values.unset): - """ - Create the WebhookInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode events: The list of space-separated events that this Webhook will subscribe to. - :param unicode webhook_url: The URL associated with this Webhook. - :param unicode webhook_method: The method to be used when calling the webhook's URL. - - :returns: The created WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'Events': events, - 'WebhookUrl': webhook_url, - 'WebhookMethod': webhook_method, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return WebhookInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a WebhookContext - - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - """ - return WebhookContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a WebhookContext - - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - """ - return WebhookContext(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 WebhookPage(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 WebhookPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The SID of the Assistant that is the parent of the resource - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookPage - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookPage - """ - super(WebhookPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of WebhookInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - return WebhookInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WebhookContext(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 WebhookContext - - :param Version version: Version that contains the resource - :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch - :param sid: The unique string that identifies the resource to fetch - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - """ - super(WebhookContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Webhooks/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the WebhookInstance - - :returns: The fetched WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, unique_name=values.unset, events=values.unset, - webhook_url=values.unset, webhook_method=values.unset): - """ - Update the WebhookInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode events: The list of space-separated events that this Webhook will subscribe to. - :param unicode webhook_url: The URL associated with this Webhook. - :param unicode webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'Events': events, - 'WebhookUrl': webhook_url, - 'WebhookMethod': webhook_method, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the WebhookInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 WebhookInstance(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 WebhookInstance - - :returns: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - super(WebhookInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'url': payload.get('url'), - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'events': payload.get('events'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - } - - # 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: WebhookContext for this WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookContext - """ - if self._context is None: - self._context = WebhookContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def url(self): - """ - :returns: The absolute URL of the Webhook resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def assistant_sid(self): - """ - :returns: The SID of the Assistant that is the parent of the resource - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def events(self): - """ - :returns: The list of space-separated events that this Webhook is subscribed to. - :rtype: unicode - """ - return self._properties['events'] - - @property - def webhook_url(self): - """ - :returns: The URL associated with this Webhook. - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def webhook_method(self): - """ - :returns: The method used when calling the webhook's URL. - :rtype: unicode - """ - return self._properties['webhook_method'] - - def fetch(self): - """ - Fetch the WebhookInstance - - :returns: The fetched WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - return self._proxy.fetch() - - def update(self, unique_name=values.unset, events=values.unset, - webhook_url=values.unset, webhook_method=values.unset): - """ - Update the WebhookInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode events: The list of space-separated events that this Webhook will subscribe to. - :param unicode webhook_url: The URL associated with this Webhook. - :param unicode webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - :rtype: twilio.rest.autopilot.v1.assistant.webhook.WebhookInstance - """ - return self._proxy.update( - unique_name=unique_name, - events=events, - webhook_url=webhook_url, - webhook_method=webhook_method, - ) - - def delete(self): - """ - Deletes the WebhookInstance - - :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/autopilot/v1/restore_assistant.py b/twilio/rest/autopilot/v1/restore_assistant.py deleted file mode 100644 index f61848ca59..0000000000 --- a/twilio/rest/autopilot/v1/restore_assistant.py +++ /dev/null @@ -1,239 +0,0 @@ -# coding=utf-8 -r""" -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 RestoreAssistantList(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 RestoreAssistantList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantList - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantList - """ - super(RestoreAssistantList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Assistants/Restore'.format(**self._solution) - - def update(self, assistant): - """ - Update the RestoreAssistantInstance - - :param unicode assistant: The unique string that identifies the resource - - :returns: The updated RestoreAssistantInstance - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantInstance - """ - data = values.of({'Assistant': assistant, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return RestoreAssistantInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RestoreAssistantPage(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 RestoreAssistantPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantPage - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantPage - """ - super(RestoreAssistantPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RestoreAssistantInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantInstance - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantInstance - """ - return RestoreAssistantInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RestoreAssistantInstance(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): - """ - Initialize the RestoreAssistantInstance - - :returns: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantInstance - :rtype: twilio.rest.autopilot.v1.restore_assistant.RestoreAssistantInstance - """ - super(RestoreAssistantInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'unique_name': payload.get('unique_name'), - 'friendly_name': payload.get('friendly_name'), - 'needs_model_build': payload.get('needs_model_build'), - 'latest_model_build_sid': payload.get('latest_model_build_sid'), - 'log_queries': payload.get('log_queries'), - 'development_stage': payload.get('development_stage'), - 'callback_url': payload.get('callback_url'), - 'callback_events': payload.get('callback_events'), - } - - # Context - self._context = None - self._solution = {} - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def needs_model_build(self): - """ - :returns: Whether model needs to be rebuilt - :rtype: bool - """ - return self._properties['needs_model_build'] - - @property - def latest_model_build_sid(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['latest_model_build_sid'] - - @property - def log_queries(self): - """ - :returns: Whether queries should be logged and kept after training - :rtype: bool - """ - return self._properties['log_queries'] - - @property - def development_stage(self): - """ - :returns: A string describing the state of the assistant. - :rtype: unicode - """ - return self._properties['development_stage'] - - @property - def callback_url(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['callback_url'] - - @property - def callback_events(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['callback_events'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - 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 index 876febf040..3a28fb5744 100644 --- a/twilio/rest/bulkexports/__init__.py +++ b/twilio/rest/bulkexports/__init__.py @@ -1,60 +1,25 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.bulkexports.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Bulkexports Domain - - :returns: Domain for Bulkexports - :rtype: twilio.rest.bulkexports.Bulkexports - """ - super(Bulkexports, self).__init__(twilio) - - self.base_url = 'https://bulkexports.twilio.com' - - # Versions - self._v1 = None - +class Bulkexports(BulkexportsBase): @property - def v1(self): - """ - :returns: Version v1 of bulkexports - :rtype: twilio.rest.bulkexports.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def exports(self): - """ - :rtype: twilio.rest.bulkexports.v1.export.ExportList - """ + def exports(self) -> ExportList: + warn( + "exports is deprecated. Use v1.exports instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.exports @property - def export_configuration(self): - """ - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationList - """ + def export_configuration(self) -> ExportConfigurationList: + warn( + "export_configuration is deprecated. Use v1.export_configuration instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.export_configuration - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/bulkexports/v1/__init__.py b/twilio/rest/bulkexports/v1/__init__.py index 471184c727..a888fb484f 100644 --- a/twilio/rest/bulkexports/v1/__init__.py +++ b/twilio/rest/bulkexports/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Bulkexports - :returns: V1 version of Bulkexports - :rtype: twilio.rest.bulkexports.v1.V1.V1 + :param domain: The Twilio.bulkexports domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._exports = None - self._export_configuration = None + super().__init__(domain, "v1") + self._exports: Optional[ExportList] = None + self._export_configuration: Optional[ExportConfigurationList] = None @property - def exports(self): - """ - :rtype: twilio.rest.bulkexports.v1.export.ExportList - """ + def exports(self) -> ExportList: if self._exports is None: self._exports = ExportList(self) return self._exports @property - def export_configuration(self): - """ - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationList - """ + def export_configuration(self) -> ExportConfigurationList: if self._export_configuration is None: self._export_configuration = ExportConfigurationList(self) return self._export_configuration - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/bulkexports/v1/export/__init__.py b/twilio/rest/bulkexports/v1/export/__init__.py index fa7de4f6e7..0ebf3a451b 100644 --- a/twilio/rest/bulkexports/v1/export/__init__.py +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -1,295 +1,250 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page +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 ExportList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "ExportContext": """ - Initialize the ExportList - - :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.bulkexports.v1.export.ExportList - :rtype: twilio.rest.bulkexports.v1.export.ExportList + :returns: ExportContext for this ExportInstance """ - super(ExportList, self).__init__(version) - - # Path Solution - self._solution = {} - - # Components - self._jobs = None + if self._context is None: + self._context = ExportContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context - @property - def jobs(self): + def fetch(self) -> "ExportInstance": """ - Access the jobs + Fetch the ExportInstance + - :returns: twilio.rest.bulkexports.v1.export.job.JobList - :rtype: twilio.rest.bulkexports.v1.export.job.JobList + :returns: The fetched ExportInstance """ - if self._jobs is None: - self._jobs = JobList(self._version, ) - return self._jobs + return self._proxy.fetch() - def get(self, resource_type): + async def fetch_async(self) -> "ExportInstance": """ - Constructs a ExportContext + Asynchronous coroutine to fetch the ExportInstance - :param resource_type: The type of communication – Messages, Calls - :returns: twilio.rest.bulkexports.v1.export.ExportContext - :rtype: twilio.rest.bulkexports.v1.export.ExportContext + :returns: The fetched ExportInstance """ - return ExportContext(self._version, resource_type=resource_type, ) + return await self._proxy.fetch_async() - def __call__(self, resource_type): + @property + def days(self) -> DayList: """ - Constructs a ExportContext - - :param resource_type: The type of communication – Messages, Calls + Access the days + """ + return self._proxy.days - :returns: twilio.rest.bulkexports.v1.export.ExportContext - :rtype: twilio.rest.bulkexports.v1.export.ExportContext + @property + def export_custom_jobs(self) -> ExportCustomJobList: """ - return ExportContext(self._version, resource_type=resource_type, ) + Access the export_custom_jobs + """ + return self._proxy.export_custom_jobs - 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 ExportPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExportContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, resource_type: str): """ - Initialize the ExportPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ExportContext - :returns: twilio.rest.bulkexports.v1.export.ExportPage - :rtype: twilio.rest.bulkexports.v1.export.ExportPage + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - super(ExportPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ExportInstance: """ - Build an instance of ExportInstance + Fetch the ExportInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.bulkexports.v1.export.ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance + :returns: The fetched ExportInstance """ - return ExportInstance(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 ExportContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) - def __init__(self, version, resource_type): + async def fetch_async(self) -> ExportInstance: """ - Initialize the ExportContext + Asynchronous coroutine to fetch the ExportInstance - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls - :returns: twilio.rest.bulkexports.v1.export.ExportContext - :rtype: twilio.rest.bulkexports.v1.export.ExportContext + :returns: The fetched ExportInstance """ - super(ExportContext, self).__init__(version) - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._days = None - self._export_custom_jobs = None + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the ExportInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: The fetched ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], ) + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) @property - def days(self): + def days(self) -> DayList: """ Access the days - - :returns: twilio.rest.bulkexports.v1.export.day.DayList - :rtype: twilio.rest.bulkexports.v1.export.day.DayList """ if self._days is None: - self._days = DayList(self._version, resource_type=self._solution['resource_type'], ) + self._days = DayList( + self._version, + self._solution["resource_type"], + ) return self._days @property - def export_custom_jobs(self): + def export_custom_jobs(self) -> ExportCustomJobList: """ Access the export_custom_jobs - - :returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList """ if self._export_custom_jobs is None: self._export_custom_jobs = ExportCustomJobList( self._version, - resource_type=self._solution['resource_type'], + self._solution["resource_type"], ) return self._export_custom_jobs - 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 ExportInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, resource_type=None): - """ - Initialize the ExportInstance +class ExportList(ListResource): - :returns: twilio.rest.bulkexports.v1.export.ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance + def __init__(self, version: Version): """ - super(ExportInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'resource_type': payload.get('resource_type'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type or self._properties['resource_type'], } + Initialize the ExportList - @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 + :param version: Version that contains the resource - :returns: ExportContext for this ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportContext """ - if self._context is None: - self._context = ExportContext(self._version, resource_type=self._solution['resource_type'], ) - return self._context + super().__init__(version) - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] + self._uri = "/Exports" - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] + self._jobs: Optional[JobList] = None @property - def links(self): + def jobs(self) -> JobList: """ - :returns: Nested resource URLs. - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch the ExportInstance - - :returns: The fetched ExportInstance - :rtype: twilio.rest.bulkexports.v1.export.ExportInstance + Access the jobs """ - return self._proxy.fetch() + if self._jobs is None: + self._jobs = JobList(self._version) + return self._jobs - @property - def days(self): + def get(self, resource_type: str) -> ExportContext: """ - Access the days + Constructs a ExportContext - :returns: twilio.rest.bulkexports.v1.export.day.DayList - :rtype: twilio.rest.bulkexports.v1.export.day.DayList + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - return self._proxy.days + return ExportContext(self._version, resource_type=resource_type) - @property - def export_custom_jobs(self): + def __call__(self, resource_type: str) -> ExportContext: """ - Access the export_custom_jobs + Constructs a ExportContext - :returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - return self._proxy.export_custom_jobs + return ExportContext(self._version, resource_type=resource_type) - 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/bulkexports/v1/export/day.py b/twilio/rest/bulkexports/v1/export/day.py index 60bf1c3d7c..f4b2a0650f 100644 --- a/twilio/rest/bulkexports/v1/export/day.py +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -1,368 +1,431 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource +from twilio.base.version import Version from twilio.base.page import Page -class DayList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, resource_type): + @property + def _proxy(self) -> "DayContext": """ - Initialize the DayList - - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls + 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.bulkexports.v1.export.day.DayList - :rtype: twilio.rest.bulkexports.v1.export.day.DayList + :returns: DayContext for this DayInstance """ - super(DayList, self).__init__(version) - - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Days'.format(**self._solution) + if self._context is None: + self._context = DayContext( + self._version, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return self._context - def stream(self, next_token=values.unset, previous_token=values.unset, - limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the DayInstance - :param unicode next_token: The next_token - :param unicode previous_token: The previous_token - :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.bulkexports.v1.export.day.DayInstance] + :returns: The fetched DayInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page( - next_token=next_token, - previous_token=previous_token, - page_size=limits['page_size'], - ) + async def fetch_async(self) -> "DayInstance": + """ + Asynchronous coroutine to fetch the DayInstance - return self._version.stream(page, limits['limit']) - def list(self, next_token=values.unset, previous_token=values.unset, limit=None, - page_size=None): + :returns: The fetched 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 unicode next_token: The next_token - :param unicode previous_token: The previous_token - :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.bulkexports.v1.export.day.DayInstance] + def __repr__(self) -> str: """ - return list(self.stream( - next_token=next_token, - previous_token=previous_token, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - def page(self, next_token=values.unset, previous_token=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of DayInstance 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 next_token: The next_token - :param unicode previous_token: The previous_token - :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.bulkexports.v1.export.day.DayPage +class DayContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str, day: str): """ - data = values.of({ - 'NextToken': next_token, - 'PreviousToken': previous_token, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the DayContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return DayPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "resource_type": resource_type, + "day": day, + } + self._uri = "/Exports/{resource_type}/Days/{day}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> DayInstance: """ - Retrieve a specific page of DayInstance records from the API. - Request is executed immediately + Fetch the DayInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayPage + :returns: The fetched DayInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return DayPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, day): - """ - Constructs a DayContext + headers["Accept"] = "application/json" - :param day: The date of the data in the file + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.bulkexports.v1.export.day.DayContext - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext - """ - return DayContext(self._version, resource_type=self._solution['resource_type'], day=day, ) + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) - def __call__(self, day): + async def fetch_async(self) -> DayInstance: """ - Constructs a DayContext + Asynchronous coroutine to fetch the DayInstance - :param day: The date of the data in the file - :returns: twilio.rest.bulkexports.v1.export.day.DayContext - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext + :returns: The fetched DayInstance """ - return DayContext(self._version, resource_type=self._solution['resource_type'], day=day, ) - 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 DayPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the DayPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param resource_type: The type of communication – Messages, Calls + Provide a friendly representation - :returns: twilio.rest.bulkexports.v1.export.day.DayPage - :rtype: twilio.rest.bulkexports.v1.export.day.DayPage + :returns: Machine friendly representation """ - super(DayPage, 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 DayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DayInstance: """ Build an instance of DayInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.bulkexports.v1.export.day.DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + :param payload: Payload response from the API """ - return DayInstance(self._version, payload, resource_type=self._solution['resource_type'], ) + return DayInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class DayContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DayList(ListResource): - def __init__(self, version, resource_type, day): + def __init__(self, version: Version, resource_type: str): """ - Initialize the DayContext + Initialize the DayList - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls - :param day: The date of the data in the file + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants - :returns: twilio.rest.bulkexports.v1.export.day.DayContext - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext """ - super(DayContext, self).__init__(version) + 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): - """ - Fetch the DayInstance + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Days".format(**self._solution) - :returns: The fetched DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DayInstance]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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. - return DayInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - day=self._solution['day'], - ) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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[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. -class DayInstance(InstanceResource): - """ 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, payload, resource_type, day=None): + :returns: Generator that will yield up to limit results """ - Initialize the DayInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.bulkexports.v1.export.day.DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: """ - super(DayInstance, self).__init__(version) + Lists DayInstance 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 = { - 'redirect_to': payload.get('redirect_to'), - 'day': payload.get('day'), - 'size': deserialize.integer(payload.get('size')), - 'create_date': payload.get('create_date'), - 'friendly_name': payload.get('friendly_name'), - 'resource_type': payload.get('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) - # Context - self._context = None - self._solution = {'resource_type': resource_type, 'day': day or self._properties['day'], } + :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[DayInstance]: """ - 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 DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: DayContext for this DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = DayContext( - self._version, - resource_type=self._solution['resource_type'], - day=self._solution['day'], + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def redirect_to(self): - """ - :returns: The redirect_to - :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, + ) -> DayPage: """ - return self._properties['redirect_to'] + Retrieve a single page of DayInstance records from the API. + Request is executed immediately - @property - def day(self): - """ - :returns: The date of the data in the file - :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 DayInstance """ - return self._properties['day'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def size(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 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: """ - :returns: Size of the file in bytes - :rtype: unicode + 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 """ - return self._properties['size'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def create_date(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 DayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DayPage: """ - :returns: The date when resource is created - :rtype: unicode + 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 """ - return self._properties['create_date'] + response = self._version.domain.twilio.request("GET", target_url) + return DayPage(self._version, response, self._solution) - @property - def friendly_name(self): + async def get_page_async(self, target_url: str) -> DayPage: """ - :returns: The friendly name specified when creating the job - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DayPage(self._version, response, self._solution) - @property - def resource_type(self): + def get(self, day: str) -> DayContext: """ - :returns: The type of communication – Messages, Calls - :rtype: unicode + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day """ - return self._properties['resource_type'] + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) - def fetch(self): + def __call__(self, day: str) -> DayContext: """ - Fetch the DayInstance + Constructs a DayContext - :returns: The fetched DayInstance - :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance + :param day: The ISO 8601 format date of the resources in the file, for a UTC day """ - return self._proxy.fetch() + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) - 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/bulkexports/v1/export/export_custom_job.py b/twilio/rest/bulkexports/v1/export/export_custom_job.py index e52685482d..72d0e9b328 100644 --- a/twilio/rest/bulkexports/v1/export/export_custom_job.py +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -1,333 +1,400 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 ExportCustomJobList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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" + ) - def __init__(self, version, resource_type): - """ - Initialize the ExportCustomJobList + self._solution = { + "resource_type": resource_type, + } - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobList + :returns: Machine friendly representation """ - super(ExportCustomJobList, self).__init__(version) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Jobs'.format(**self._solution) - def stream(self, next_token=values.unset, previous_token=values.unset, - limit=None, page_size=None): +class ExportCustomJobPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> 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. + Build an instance of ExportCustomJobInstance - :param unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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 payload: Payload response from the API + """ + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance] + def __repr__(self) -> str: """ - limits = self._version.read_limits(limit, page_size) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - page = self.page( - next_token=next_token, - previous_token=previous_token, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit']) +class ExportCustomJobList(ListResource): - def list(self, next_token=values.unset, previous_token=values.unset, limit=None, - page_size=None): + def __init__(self, version: Version, resource_type: str): """ - Lists ExportCustomJobInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Initialize the ExportCustomJobList - :param unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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 version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance] """ - return list(self.stream( - next_token=next_token, - previous_token=previous_token, - limit=limit, - page_size=page_size, - )) - - def page(self, next_token=values.unset, previous_token=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + 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: """ - Retrieve a single page of ExportCustomJobInstance records from the API. - Request is executed immediately + Create the ExportCustomJobInstance - :param unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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 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: Page of ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobPage + :returns: The created ExportCustomJobInstance """ - data = values.of({ - 'NextToken': next_token, - 'PreviousToken': previous_token, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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"}) - return ExportCustomJobPage(self._version, response, self._solution) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def get_page(self, target_url): - """ - Retrieve a specific page of ExportCustomJobInstance records from the API. - Request is executed immediately + headers["Accept"] = "application/json" - :param str target_url: API-generated URL for the requested results page + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Page of ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] ) - return ExportCustomJobPage(self._version, response, self._solution) + 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. - def create(self, friendly_name=values.unset, start_day=values.unset, - end_day=values.unset, webhook_url=values.unset, - webhook_method=values.unset, email=values.unset): + :returns: The created ExportCustomJobInstance """ - Create the ExportCustomJobInstance - :param unicode friendly_name: The friendly_name - :param unicode start_day: The start_day - :param unicode end_day: The end_day - :param unicode webhook_url: The webhook_url - :param unicode webhook_method: The webhook_method - :param unicode email: The email + 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"}) - :returns: The created ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'StartDay': start_day, - 'EndDay': end_day, - 'WebhookUrl': webhook_url, - 'WebhookMethod': webhook_method, - 'Email': email, - }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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'], + self._version, payload, resource_type=self._solution["resource_type"] ) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExportCustomJobInstance]: """ - Provide a friendly representation + 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. - :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 ExportCustomJobPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + 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[ExportCustomJobInstance]: """ - Initialize the ExportCustomJobPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API - :param resource_type: The type of communication – Messages, Calls + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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.bulkexports.v1.export.export_custom_job.ExportCustomJobPage - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobPage + :returns: Generator that will yield up to limit results """ - super(ExportCustomJobPage, 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[ExportCustomJobInstance]: """ - Build an instance of 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 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.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance + :returns: list that will contain up to limit results """ - return ExportCustomJobInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], + 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[ExportCustomJobInstance]: """ - Provide a friendly representation + 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. - :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, + ) -> ExportCustomJobPage: """ - return '' - + Retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately -class ExportCustomJobInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + :param page_token: PageToken provided by the 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, resource_type): + :returns: Page of ExportCustomJobInstance """ - Initialize the ExportCustomJobInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance - :rtype: twilio.rest.bulkexports.v1.export.export_custom_job.ExportCustomJobInstance - """ - super(ExportCustomJobInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload.get('friendly_name'), - 'resource_type': payload.get('resource_type'), - 'start_day': payload.get('start_day'), - 'end_day': payload.get('end_day'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'email': payload.get('email'), - 'job_sid': payload.get('job_sid'), - 'details': payload.get('details'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'resource_type': resource_type, } + headers["Accept"] = "application/json" - @property - def friendly_name(self): - """ - :returns: The friendly name specified when creating the job - :rtype: unicode - """ - return self._properties['friendly_name'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :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, + ) -> ExportCustomJobPage: """ - return self._properties['resource_type'] + Asynchronously retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately - @property - def start_day(self): - """ - :returns: The start time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['start_day'] + :param page_token: PageToken provided by the 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 end_day(self): - """ - :returns: The end time for the export specified when creating the job - :rtype: unicode + :returns: Page of ExportCustomJobInstance """ - return self._properties['end_day'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def webhook_url(self): - """ - :returns: The optional webhook url called on completion - :rtype: unicode - """ - return self._properties['webhook_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def webhook_method(self): - """ - :returns: This is the method used to call the webhook - :rtype: unicode - """ - return self._properties['webhook_method'] + headers["Accept"] = "application/json" - @property - def email(self): - """ - :returns: The optional email to send the completion notification to - :rtype: unicode - """ - return self._properties['email'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) - @property - def job_sid(self): + def get_page(self, target_url: str) -> ExportCustomJobPage: """ - :returns: The job_sid returned when the export was created - :rtype: unicode + 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 """ - return self._properties['job_sid'] + response = self._version.domain.twilio.request("GET", target_url) + return ExportCustomJobPage(self._version, response, self._solution) - @property - def details(self): + async def get_page_async(self, target_url: str) -> ExportCustomJobPage: """ - :returns: The details - :rtype: dict + 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 """ - return self._properties['details'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExportCustomJobPage(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/bulkexports/v1/export/job.py b/twilio/rest/bulkexports/v1/export/job.py index eaf31cb16e..5358ffa83a 100644 --- a/twilio/rest/bulkexports/v1/export/job.py +++ b/twilio/rest/bulkexports/v1/export/job.py @@ -1,307 +1,253 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page +from twilio.base.version import Version -class JobList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "JobContext": """ - Initialize the JobList - - :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.bulkexports.v1.export.job.JobList - :rtype: twilio.rest.bulkexports.v1.export.job.JobList + :returns: JobContext for this JobInstance """ - super(JobList, self).__init__(version) - - # Path Solution - self._solution = {} + if self._context is None: + self._context = JobContext( + self._version, + job_sid=self._solution["job_sid"], + ) + return self._context - def get(self, job_sid): + def delete(self) -> bool: """ - Constructs a JobContext - - :param job_sid: The job_sid + Deletes the JobInstance - :returns: twilio.rest.bulkexports.v1.export.job.JobContext - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext - """ - return JobContext(self._version, job_sid=job_sid, ) - def __call__(self, job_sid): + :returns: True if delete succeeds, False otherwise """ - Constructs a JobContext - - :param job_sid: The job_sid + return self._proxy.delete() - :returns: twilio.rest.bulkexports.v1.export.job.JobContext - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext + async def delete_async(self) -> bool: """ - return JobContext(self._version, job_sid=job_sid, ) + Asynchronous coroutine that deletes the JobInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' - + return await self._proxy.delete_async() -class JobPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, response, solution): + def fetch(self) -> "JobInstance": """ - Initialize the JobPage + Fetch the JobInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.bulkexports.v1.export.job.JobPage - :rtype: twilio.rest.bulkexports.v1.export.job.JobPage + :returns: The fetched JobInstance """ - super(JobPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch() - def get_instance(self, payload): + async def fetch_async(self) -> "JobInstance": """ - Build an instance of JobInstance + Asynchronous coroutine to fetch the JobInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.bulkexports.v1.export.job.JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobInstance + :returns: The fetched JobInstance """ - return JobInstance(self._version, payload, ) + 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 JobContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, job_sid): + def __init__(self, version: Version, job_sid: str): """ Initialize the JobContext - :param Version version: Version that contains the resource - :param job_sid: The job_sid - - :returns: twilio.rest.bulkexports.v1.export.job.JobContext - :rtype: twilio.rest.bulkexports.v1.export.job.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(JobContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'job_sid': job_sid, } - self._uri = '/Exports/Jobs/{job_sid}'.format(**self._solution) + self._solution = { + "job_sid": job_sid, + } + self._uri = "/Exports/Jobs/{job_sid}".format(**self._solution) - def fetch(self): + def delete(self) -> bool: """ - Fetch the JobInstance + Deletes the JobInstance - :returns: The fetched JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobInstance + + :returns: True if delete succeeds, False otherwise """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return JobInstance(self._version, payload, job_sid=self._solution['job_sid'], ) + headers = values.of({}) - def delete(self): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Deletes the JobInstance + Asynchronous coroutine that deletes the JobInstance + :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> JobInstance: """ - Provide a friendly representation + Fetch the JobInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched JobInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class JobInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, job_sid=None): - """ - Initialize the JobInstance - - :returns: twilio.rest.bulkexports.v1.export.job.JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobInstance - """ - super(JobInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'resource_type': payload.get('resource_type'), - 'friendly_name': payload.get('friendly_name'), - 'details': payload.get('details'), - 'start_day': payload.get('start_day'), - 'end_day': payload.get('end_day'), - 'job_sid': payload.get('job_sid'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'email': payload.get('email'), - 'url': payload.get('url'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'job_sid': job_sid or self._properties['job_sid'], } + payload = self._version.fetch(method="GET", uri=self._uri, 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 JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) - :returns: JobContext for this JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobContext + async def fetch_async(self) -> JobInstance: """ - if self._context is None: - self._context = JobContext(self._version, job_sid=self._solution['job_sid'], ) - return self._context + Asynchronous coroutine to fetch the JobInstance - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - @property - def friendly_name(self): - """ - :returns: The friendly name specified when creating the job - :rtype: unicode + :returns: The fetched JobInstance """ - return self._properties['friendly_name'] - @property - def details(self): - """ - :returns: This is a list of the completed, pending, or errored dates within the export time range, with one entry for each status with more than one day in that status - :rtype: dict - """ - return self._properties['details'] + headers = values.of({}) - @property - def start_day(self): - """ - :returns: The start time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['start_day'] + headers["Accept"] = "application/json" - @property - def end_day(self): - """ - :returns: The end time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['end_day'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def job_sid(self): - """ - :returns: The job_sid returned when the export was created - :rtype: unicode - """ - return self._properties['job_sid'] + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) - @property - def webhook_url(self): - """ - :returns: The optional webhook url called on completion - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['webhook_url'] + Provide a friendly representation - @property - def webhook_method(self): - """ - :returns: This is the method used to call the webhook - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['webhook_method'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def email(self): - """ - :returns: The optional email to send the completion notification to - :rtype: unicode - """ - return self._properties['email'] - @property - def url(self): +class JobList(ListResource): + + def __init__(self, version: Version): """ - :returns: The url - :rtype: unicode + Initialize the JobList + + :param version: Version that contains the resource + """ - return self._properties['url'] + super().__init__(version) - def fetch(self): + def get(self, job_sid: str) -> JobContext: """ - Fetch the JobInstance + Constructs a JobContext - :returns: The fetched JobInstance - :rtype: twilio.rest.bulkexports.v1.export.job.JobInstance + :param job_sid: The unique string that that we created to identify the Bulk Export job """ - return self._proxy.fetch() + return JobContext(self._version, job_sid=job_sid) - def delete(self): + def __call__(self, job_sid: str) -> JobContext: """ - Deletes the JobInstance + Constructs a JobContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param job_sid: The unique string that that we created to identify the Bulk Export job """ - return self._proxy.delete() + return JobContext(self._version, job_sid=job_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/bulkexports/v1/export_configuration.py b/twilio/rest/bulkexports/v1/export_configuration.py index 3f25f8043e..207642769b 100644 --- a/twilio/rest/bulkexports/v1/export_configuration.py +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -1,287 +1,312 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 twilio.base import values +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 ExportConfigurationList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "ExportConfigurationContext": """ - Initialize the ExportConfigurationList - - :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.bulkexports.v1.export_configuration.ExportConfigurationList - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationList + :returns: ExportConfigurationContext for this ExportConfigurationInstance """ - super(ExportConfigurationList, self).__init__(version) - - # Path Solution - self._solution = {} + if self._context is None: + self._context = ExportConfigurationContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context - def get(self, resource_type): + def fetch(self) -> "ExportConfigurationInstance": """ - Constructs a ExportConfigurationContext - - :param resource_type: The type of communication – Messages, Calls + Fetch the ExportConfigurationInstance - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext - """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) - def __call__(self, resource_type): + :returns: The fetched ExportConfigurationInstance """ - Constructs a ExportConfigurationContext - - :param resource_type: The type of communication – Messages, Calls + return self._proxy.fetch() - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext + async def fetch_async(self) -> "ExportConfigurationInstance": """ - return ExportConfigurationContext(self._version, resource_type=resource_type, ) + Asynchronous coroutine to fetch the ExportConfigurationInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched ExportConfigurationInstance """ - return '' - - -class ExportConfigurationPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": """ - Initialize the ExportConfigurationPage + Update the ExportConfigurationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationPage - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationPage + :returns: The updated ExportConfigurationInstance """ - super(ExportConfigurationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.update( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) - def get_instance(self, payload): + 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": """ - Build an instance of ExportConfigurationInstance + Asynchronous coroutine to update the ExportConfigurationInstance - :param dict payload: Payload response from the API + :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: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + :returns: The updated ExportConfigurationInstance """ - return ExportConfigurationInstance(self._version, payload, ) + return await self._proxy.update_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) - 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 ExportConfigurationContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, resource_type): + def __init__(self, version: Version, resource_type: str): """ Initialize the ExportConfigurationContext - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls - - :returns: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - super(ExportConfigurationContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Configuration'.format(**self._solution) + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Configuration".format(**self._solution) - def fetch(self): + def fetch(self) -> ExportConfigurationInstance: """ Fetch the ExportConfigurationInstance + :returns: The fetched ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + resource_type=self._solution["resource_type"], ) - def update(self, enabled=values.unset, webhook_url=values.unset, - webhook_method=values.unset): + async def fetch_async(self) -> ExportConfigurationInstance: """ - Update the ExportConfigurationInstance + Asynchronous coroutine to fetch the ExportConfigurationInstance - :param bool enabled: Whether files are automatically generated - :param unicode webhook_url: URL targeted at export - :param unicode webhook_method: Whether to GET or POST to the webhook url - :returns: The updated ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + :returns: The fetched ExportConfigurationInstance """ - data = values.of({'Enabled': enabled, 'WebhookUrl': webhook_url, 'WebhookMethod': webhook_method, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + resource_type=self._solution["resource_type"], ) - def __repr__(self): + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: """ - Provide a friendly representation + Update the ExportConfigurationInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) -class ExportConfigurationInstance(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" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __init__(self, version, payload, resource_type=None): + 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: """ - Initialize the 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: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + :returns: The updated ExportConfigurationInstance """ - super(ExportConfigurationInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'enabled': payload.get('enabled'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'resource_type': payload.get('resource_type'), - 'url': payload.get('url'), - } + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) - # Context - self._context = None - self._solution = {'resource_type': resource_type or self._properties['resource_type'], } + 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: ExportConfigurationContext for this ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationContext - """ - if self._context is None: - self._context = ExportConfigurationContext( - self._version, - resource_type=self._solution['resource_type'], - ) - return self._context + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def enabled(self): - """ - :returns: Whether files are automatically generated - :rtype: bool - """ - return self._properties['enabled'] + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) - @property - def webhook_url(self): + def __repr__(self) -> str: """ - :returns: URL targeted at export - :rtype: unicode - """ - return self._properties['webhook_url'] + Provide a friendly representation - @property - def webhook_method(self): - """ - :returns: Whether to GET or POST to the webhook url - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['webhook_method'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode +class ExportConfigurationList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['url'] + Initialize the ExportConfigurationList + + :param version: Version that contains the resource - def fetch(self): """ - Fetch the ExportConfigurationInstance + super().__init__(version) - :returns: The fetched ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + def get(self, resource_type: str) -> ExportConfigurationContext: """ - return self._proxy.fetch() + Constructs a ExportConfigurationContext - def update(self, enabled=values.unset, webhook_url=values.unset, - webhook_method=values.unset): + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - Update the ExportConfigurationInstance + return ExportConfigurationContext(self._version, resource_type=resource_type) - :param bool enabled: Whether files are automatically generated - :param unicode webhook_url: URL targeted at export - :param unicode webhook_method: Whether to GET or POST to the webhook url + def __call__(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext - :returns: The updated ExportConfigurationInstance - :rtype: twilio.rest.bulkexports.v1.export_configuration.ExportConfigurationInstance + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants """ - return self._proxy.update(enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method, ) + return ExportConfigurationContext(self._version, resource_type=resource_type) - 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/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 dcd10545c1..9608a0fd87 100644 --- a/twilio/rest/chat/__init__.py +++ b/twilio/rest/chat/__init__.py @@ -1,72 +1,35 @@ -# coding=utf-8 -r""" -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 317a2bf1e5..d0ade9eed5 100644 --- a/twilio/rest/chat/v1/__init__.py +++ b/twilio/rest/chat/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 6fec3c2155..3bd48b1144 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -1,454 +1,711 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class CredentialInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CredentialList + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList + @property + def _proxy(self) -> "CredentialContext": """ - super(CredentialList, 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 = '/Credentials'.format(**self._solution) + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the CredentialInstance - :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.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 await self._proxy.delete_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) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + + :returns: The fetched CredentialInstance """ - 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) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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: The fetched CredentialInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return CredentialPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The updated CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Create the CredentialInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param CredentialInstance.PushService type: The type of push-notification service the credential is for - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + Initialize the CredentialContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) - return CredentialInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CredentialContext + Deletes the CredentialInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: True if delete succeeds, False otherwise """ - return CredentialContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CredentialContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + async def delete_async(self) -> bool: """ - return CredentialContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CredentialInstance - 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 CredentialPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialPage + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - super(CredentialPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of CredentialInstance + 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.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialInstance """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the CredentialContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + 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: """ - super(CredentialContext, self).__init__(version) + Update the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + :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. - def fetch(self): + :returns: The updated CredentialInstance """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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: """ - Update the CredentialInstance + Asynchronous coroutine to update the CredentialInstance - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the CredentialInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'sandbox': payload.get('sandbox'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: """ - return self._properties['sid'] + Create the CredentialInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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 """ - 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 = 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 string that you assigned to describe the resource - :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 of push-notification service the credential is for - :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: [APN only] Whether to send the credential to sandbox APNs - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the Credential 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 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 the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: The 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: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 34d727f2e3..26fde4025b 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -1,913 +1,1359 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 the ServiceInstance + Deletes the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :returns: The 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(method='POST', uri=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']) - - 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": """ - 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.chat.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 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 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: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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. - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + 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, + ) - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + @property + def channels(self) -> ChannelList: """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): + Access the channels """ - Constructs a ServiceContext + return self._proxy.channels - :param sid: The unique string that identifies the resource + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + @property + def users(self) -> UserList: + """ + 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 unique string that identifies the resource - :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 the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of WebHook events that are enabled for this Service instance - :param unicode webhooks_on_message_send_url: The URL of the webhook to call in response to the on_message_send event - :param unicode webhooks_on_message_send_method: The HTTP method to use when calling the webhooks.on_message_send.url - :param unicode webhooks_on_message_update_url: The URL of the webhook to call in response to the on_message_update event - :param unicode webhooks_on_message_update_method: The HTTP method to use when calling the webhooks.on_message_update.url - :param unicode webhooks_on_message_remove_url: The URL of the webhook to call in response to the on_message_remove event - :param unicode webhooks_on_message_remove_method: The HTTP method to use when calling the webhooks.on_message_remove.url - :param unicode webhooks_on_channel_add_url: The URL of the webhook to call in response to the on_channel_add event - :param unicode webhooks_on_channel_add_method: The HTTP method to use when calling the webhooks.on_channel_add.url - :param unicode webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the on_channel_destroy event - :param unicode webhooks_on_channel_destroy_method: The HTTP method to use when calling the webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_update_url: The URL of the webhook to call in response to the on_channel_update event - :param unicode webhooks_on_channel_update_method: The HTTP method to use when calling the webhooks.on_channel_update.url - :param unicode webhooks_on_member_add_url: The URL of the webhook to call in response to the on_member_add event - :param unicode webhooks_on_member_add_method: The HTTP method to use when calling the webhooks.on_member_add.url - :param unicode webhooks_on_member_remove_url: The URL of the webhook to call in response to the on_member_remove event - :param unicode webhooks_on_member_remove_method: The HTTP method to use when calling the webhooks.on_member_remove.url - :param unicode webhooks_on_message_sent_url: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_sent_method: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_updated_url: The URL of the webhook to call in response to the on_message_updated event - :param unicode webhooks_on_message_updated_method: The HTTP method to use when calling the webhooks.on_message_updated.url - :param unicode webhooks_on_message_removed_url: The URL of the webhook to call in response to the on_message_removed event - :param unicode webhooks_on_message_removed_method: The HTTP method to use when calling the webhooks.on_message_removed.url - :param unicode webhooks_on_channel_added_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_added_method: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_method: The HTTP method to use when calling the webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_updated_url: he URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_channel_updated_method: The HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_added_url: The URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_member_added_method: he HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_removed_url: The URL of the webhook to call in response to the on_member_removed event - :param unicode webhooks_on_member_removed_method: The HTTP method to use when calling the webhooks.on_member_removed.url - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. :returns: The updated ServiceInstance - :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.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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def channels(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'default_service_role_sid': payload.get('default_service_role_sid'), - 'default_channel_role_sid': payload.get('default_channel_role_sid'), - 'default_channel_creator_role_sid': payload.get('default_channel_creator_role_sid'), - 'read_status_enabled': payload.get('read_status_enabled'), - 'reachability_enabled': payload.get('reachability_enabled'), - 'typing_indicator_timeout': deserialize.integer(payload.get('typing_indicator_timeout')), - 'consumption_report_interval': deserialize.integer(payload.get('consumption_report_interval')), - 'limits': payload.get('limits'), - 'webhooks': payload.get('webhooks'), - 'pre_webhook_url': payload.get('pre_webhook_url'), - 'post_webhook_url': payload.get('post_webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'webhook_filters': payload.get('webhook_filters'), - 'notifications': payload.get('notifications'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 service role assigned to users when they are added to the service - :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 channel role assigned to users when they are added to a channel - :rtype: unicode - """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The channel role assigned to a channel creator when they join a new channel - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is 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: Whether the Reachability Indicator feature is enabled for this Service instance - :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: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :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: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def webhooks(self): - """ - :returns: An object that contains information about the webhooks configured for this service - :rtype: dict - """ - return self._properties['webhooks'] + headers["Accept"] = "application/json" - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :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 URL for post-event webhooks - :rtype: unicode - """ - return self._properties['post_webhook_url'] + return ServiceInstance(self._version, payload) - @property - def webhook_method(self): - """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - 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 list of WebHook events that are enabled for this Service instance - :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 notification configuration for the Service instance - :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 absolute URL of the Service 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: The absolute URLs of the Service's Channels, Roles, and Users - :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 the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.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, + } + ) + + 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 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"}) + + 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_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_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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 friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of WebHook events that are enabled for this Service instance - :param unicode webhooks_on_message_send_url: The URL of the webhook to call in response to the on_message_send event - :param unicode webhooks_on_message_send_method: The HTTP method to use when calling the webhooks.on_message_send.url - :param unicode webhooks_on_message_update_url: The URL of the webhook to call in response to the on_message_update event - :param unicode webhooks_on_message_update_method: The HTTP method to use when calling the webhooks.on_message_update.url - :param unicode webhooks_on_message_remove_url: The URL of the webhook to call in response to the on_message_remove event - :param unicode webhooks_on_message_remove_method: The HTTP method to use when calling the webhooks.on_message_remove.url - :param unicode webhooks_on_channel_add_url: The URL of the webhook to call in response to the on_channel_add event - :param unicode webhooks_on_channel_add_method: The HTTP method to use when calling the webhooks.on_channel_add.url - :param unicode webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the on_channel_destroy event - :param unicode webhooks_on_channel_destroy_method: The HTTP method to use when calling the webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_update_url: The URL of the webhook to call in response to the on_channel_update event - :param unicode webhooks_on_channel_update_method: The HTTP method to use when calling the webhooks.on_channel_update.url - :param unicode webhooks_on_member_add_url: The URL of the webhook to call in response to the on_member_add event - :param unicode webhooks_on_member_add_method: The HTTP method to use when calling the webhooks.on_member_add.url - :param unicode webhooks_on_member_remove_url: The URL of the webhook to call in response to the on_member_remove event - :param unicode webhooks_on_member_remove_method: The HTTP method to use when calling the webhooks.on_member_remove.url - :param unicode webhooks_on_message_sent_url: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_sent_method: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_updated_url: The URL of the webhook to call in response to the on_message_updated event - :param unicode webhooks_on_message_updated_method: The HTTP method to use when calling the webhooks.on_message_updated.url - :param unicode webhooks_on_message_removed_url: The URL of the webhook to call in response to the on_message_removed event - :param unicode webhooks_on_message_removed_method: The HTTP method to use when calling the webhooks.on_message_removed.url - :param unicode webhooks_on_channel_added_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_added_method: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_method: The HTTP method to use when calling the webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_updated_url: he URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_channel_updated_method: The HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_added_url: The URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_member_added_method: he HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_removed_url: The URL of the webhook to call in response to the on_member_removed event - :param unicode webhooks_on_member_removed_method: The HTTP method to use when calling the webhooks.on_member_removed.url - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service + :param target_url: API-generated URL for the requested results page - :returns: The 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_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, - ) + 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 4fc781493f..ffe42c0b5d 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -1,598 +1,790 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the ChannelList +class ChannelInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + @property + def _proxy(self) -> "ChannelContext": """ - Create the ChannelInstance - - :param unicode friendly_name: A string to describe the new resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param ChannelInstance.ChannelType type: The visibility of the channel + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: ChannelContext for this ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete(self) -> bool: + """ + 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. - - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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.channel.ChannelInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, type=values.unset, limit=None, page_size=None): + def fetch(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. + Fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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 self._proxy.fetch() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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.v1.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - data = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - return ChannelPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 specific page of ChannelInstance records from the API. - Request is executed immediately + 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 self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a ChannelContext + Asynchronous coroutine to update the ChannelInstance - :param sid: The unique string that identifies the resource + :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: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + :returns: The updated ChannelInstance """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - def __call__(self, sid): + @property + def invites(self) -> InviteList: """ - Constructs a ChannelContext + Access the invites + """ + return self._proxy.invites - :param sid: The unique string that identifies the resource + @property + def members(self) -> MemberList: + """ + 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 SID of the Service that the resource is associated with + 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 SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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 the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data + :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 - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'attributes': payload.get('attributes'), - 'type': payload.get('type'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('created_by'), - 'members_count': deserialize.integer(payload.get('members_count')), - 'messages_count': deserialize.integer(payload.get('messages_count')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The visibility of the channel. Can be: `public` or `private` - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Asynchronously create the ChannelInstance - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :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 number of Members in the Channel - :rtype: unicode + :returns: The created ChannelInstance """ - 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 number of Messages in the Channel - :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 absolute URL of the Channel resource - :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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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. - def fetch(self): + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Fetch the ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: The 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"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - def delete(self): + 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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data + :param target_url: API-generated URL for the requested results page - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + :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 a6067bd882..e5cd4ebe36 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -1,448 +1,598 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[InviteContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + :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 the InviteInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + return self._proxy.delete() - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) - 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` value of the resources to read - :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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The unique string that identifies the resource - :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 unique string that identifies the resource - :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 + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v1.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + def __repr__(self) -> str: """ - super(InvitePage, 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 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The unique string that identifies the resource + :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 the InviteInstance + Create the InviteInstance - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: """ - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'created_by': payload.get('created_by'), - 'url': payload.get('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): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Channel the new resource belongs to - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 SID of the Role assigned to the member - :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 identity of the User that created the invite - :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 absolute URL of the Invite resource - :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 the InviteInstance + Constructs a InviteContext - :returns: The 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 765afc3986..1262703ddc 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -1,496 +1,716 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[MemberContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel for the member + :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 the MemberInstance + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role to assign to the member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) + :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` value of the resources to read - :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 await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + 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 MemberInstance 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` value of the resources to read - :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.v1.service.channel.member.MemberPage +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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) - 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) -> 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 - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return MemberPage(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 MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: True if delete succeeds, False otherwise """ - return MemberContext( + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - 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 unique string that identifies the resource - :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" - def __init__(self, version, response, solution): + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: """ - 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 SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel for the member + :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 +class MemberPage(Page): - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + 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 SID of the Service to fetch the resource from - :param channel_sid: The unique ID of the channel the member belongs to - :param sid: The unique string that identifies the resource + :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 the MemberInstance + Create the MemberInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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 SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The 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(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload.get('last_consumption_timestamp')), - 'url': payload.get('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): - """ - :returns: The unique string that identifies the resource - :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 SID of the Account that created the resource - :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 unique ID of the Channel for the member - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the member - :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 index of the last Message that the Member has read within the Channel - :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 ISO 8601 based timestamp string that represents the date-time of the last Message read event for the Member within the Channel - :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 absolute URL of the Member resource - :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 the MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: The 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 SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: The 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 6ef8c07a5f..e7cfc9217d 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -1,513 +1,731 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MessageList + class OrderType(object): + ASC = "asc" + DESC = "desc" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel the Message resource belongs to + """ + :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") - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + 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": """ - super(MessageList, 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, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, body, from_=values.unset, attributes=values.unset): + def delete(self) -> bool: """ - Create the MessageInstance + Deletes the MessageInstance - :param unicode body: The message to send to the channel - :param unicode from_: The identity of the new message's author - :param unicode attributes: A valid JSON string that contains application-specific data - :returns: The 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 self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - 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 - :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.channel.message.MessageInstance] + def fetch(self) -> "MessageInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the MessageInstance - page = self.page(order=order, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() - def list(self, order=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.message.MessageInstance] + :returns: The fetched MessageInstance """ - return list(self.stream(order=order, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Update the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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 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: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return MessagePage(self._version, response, self._solution) + return self._proxy.update( + body=body, + attributes=attributes, + ) - def get_page(self, target_url): + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the MessageInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + body=body, + attributes=attributes, ) - return MessagePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a MessageContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext - """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, - ) +class MessageContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - Constructs a MessageContext - - :param sid: The unique string that identifies the resource + Initialize the MessageContext - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message belongs to. Can be the Channel's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) ) - def __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the MessageInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class MessagePage(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 MessagePage + Asynchronous coroutine that deletes the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel the Message resource belongs to - :returns: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - super(MessagePage, 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) -> MessageInstance: """ - Build an instance of MessageInstance + Fetch the MessageInstance - :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 + :returns: The fetched MessageInstance """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 MessageContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, channel_sid, sid): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Initialize the MessageContext + Update the MessageInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param channel_sid: The unique ID of the Channel the message to fetch belongs to - :param sid: The unique string that identifies the resource + :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.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :returns: The updated MessageInstance """ - super(MessageContext, self).__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) + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Fetch the MessageInstance + Asynchronous coroutine to update the MessageInstance - :returns: The 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 attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the MessageInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def update(self, body=values.unset, attributes=values.unset): - """ - Update the MessageInstance - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data +class MessagePage(Page): - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ - data = values.of({'Body': body, 'Attributes': attributes, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class MessageInstance(InstanceResource): - """ """ +class MessageList(ListResource): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'attributes': payload.get('attributes'), - 'service_sid': payload.get('service_sid'), - 'to': payload.get('to'), - 'channel_sid': payload.get('channel_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'was_edited': payload.get('was_edited'), - 'from_': payload.get('from'), - 'body': payload.get('body'), - 'index': deserialize.integer(payload.get('index')), - 'url': payload.get('url'), - } + :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`. - # Context - self._context = None + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - @property - def _proxy(self): + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the MessageInstance - :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'], - ) - return self._context + :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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers["Accept"] = "application/json" - @property - def to(self): - """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode - """ - return self._properties['to'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def channel_sid(self): - """ - :returns: The unique ID of the Channel the Message resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - return self._properties['date_created'] + Asynchronously create the MessageInstance - @property - def date_updated(self): + :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 """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - return self._properties['date_updated'] + 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 was_edited(self): + :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 """ - :returns: Whether the message has been edited since it was created - :rtype: bool + 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]: """ - return self._properties['was_edited'] + 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 from_(self): + :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 """ - :returns: The identity of the message's author - :rtype: unicode + 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]: """ - return self._properties['from_'] + 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 body(self): + :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]: """ - :returns: The content of the message - :rtype: unicode + 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: """ - return self._properties['body'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def index(self): + :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 """ - :returns: The index of the message within the Channel - :rtype: unicode + 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: """ - return self._properties['index'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the Message resource - :rtype: unicode + 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: """ - return self._properties['url'] + 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 fetch(self): + :returns: Page of MessageInstance """ - Fetch the MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: The 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 message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: The 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 12044eac9c..d81cbd55ac 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -1,442 +1,645 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the RoleList +class RoleInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList - """ - super(RoleList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None - def create(self, friendly_name, type, permission): + @property + def _proxy(self) -> "RoleContext": """ - Create the RoleInstance - - :param unicode friendly_name: A string to describe the new resource - :param RoleInstance.RoleType type: The type of role - :param unicode permission: A permission the role should have + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: RoleContext for this RoleInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the RoleInstance - :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.role.RoleInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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 that deletes 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: 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) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The fetched RoleInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RolePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RoleInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The fetched RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RolePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Update the RoleInstance - :param sid: The unique string that identifies the resource + :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: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update( + permission=permission, + ) - def __call__(self, sid): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance - :param sid: The unique string that identifies the resource + :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: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + permission=permission, + ) - 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 RolePage(Page): - """ """ +class RoleContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the RolePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the RoleContext - :returns: twilio.rest.chat.v1.service.role.RolePage - :rtype: twilio.rest.chat.v1.service.role.RolePage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. """ - super(RolePage, 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}/Roles/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RoleInstance + Deletes 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: True if delete succeeds, False otherwise """ - return RoleInstance(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 RoleInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RoleContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> RoleInstance: """ - Initialize the RoleContext + Fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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 = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: """ - Fetch the RoleInstance + Asynchronous coroutine to fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, permission): + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Update the RoleInstance + Asynchronous coroutine to update the RoleInstance - :param unicode permission: A permission the role should have + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'permissions': payload.get('permissions'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 string that you assigned to describe the resource - :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 of role - :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: An array of the permissions the role has been granted - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the Role 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance """ - Fetch the RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: The 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: A permission the role should have + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: The 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 0948f797e7..c6b900957c 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -1,521 +1,723 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + 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 the UserInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the new resource + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The 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(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 unique string that identifies the resource + :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 unique string that identifies the resource - - :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 SID of the Service that the resource is associated with + 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 SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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" - # Dependents - self._user_channels = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: """ - Fetch the UserInstance + Asynchronous coroutine to fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource + :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 - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'attributes': payload.get('attributes'), - 'friendly_name': payload.get('friendly_name'), - 'role_sid': payload.get('role_sid'), - 'identity': payload.get('identity'), - 'is_online': payload.get('is_online'), - 'is_notifiable': payload.get('is_notifiable'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'joined_channels_count': deserialize.integer(payload.get('joined_channels_count')), - 'links': payload.get('links'), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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 SID of the assigned to the user - :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 string that identifies the resource's User - :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: Whether the User is actively connected to the Service instance and 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: Whether the User has a potentially valid Push Notification registration for the Service instance - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 number of Channels this User is a Member of - :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 absolute URLs of the Channel and Binding resources related to the user - :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 absolute URL of the User 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 = 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 - 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 UserInstance """ - Fetch the UserInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + headers = values.of({"Content-Type": "application/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: """ - 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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext - :returns: The 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 dceddbb56e..b7f35aa9ef 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -1,273 +1,322 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with - :param user_sid: The unique string that identifies the resource + 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']) +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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - 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 SID of the Service that the resource is associated with - :param user_sid: The unique string that identifies the 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: 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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'member_sid': payload.get('member_sid'), - 'status': payload.get('status'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'unread_messages_count': deserialize.integer(payload.get('unread_messages_count')), - 'links': payload.get('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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + headers["Accept"] = "application/json" - @property - def member_sid(self): - """ - :returns: The SID of the User as a Member in the Channel - :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 of the User on the Channel - :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 index of the last Message in the Channel the Member has read - :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 number of unread Messages in the Channel for the User - :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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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 589cb55646..e949532d56 100644 --- a/twilio/rest/chat/v2/__init__.py +++ b/twilio/rest/chat/v2/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 5439bdbcb0..5479abeca0 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -1,454 +1,711 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class CredentialInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CredentialList + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList + @property + def _proxy(self) -> "CredentialContext": """ - super(CredentialList, 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 = '/Credentials'.format(**self._solution) + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the CredentialInstance - :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.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 await self._proxy.delete_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) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + + :returns: The fetched CredentialInstance """ - 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) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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: The fetched CredentialInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return CredentialPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The updated CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Create the CredentialInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param CredentialInstance.PushService type: The type of push-notification service the credential is for - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + Initialize the CredentialContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The SID of the Credential resource to update. + """ + super().__init__(version) - return CredentialInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CredentialContext + Deletes the CredentialInstance - :param sid: The SID of the Credential resource to fetch - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: True if delete succeeds, False otherwise """ - return CredentialContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CredentialContext + headers = values.of({}) - :param sid: The SID of the Credential resource to fetch + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + async def delete_async(self) -> bool: """ - return CredentialContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CredentialInstance - 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 CredentialPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialPage + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The fetched CredentialInstance """ - super(CredentialPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of CredentialInstance + 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.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialInstance """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the CredentialContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The SID of the Credential resource to fetch + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + 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: """ - super(CredentialContext, self).__init__(version) + Update the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + :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. - def fetch(self): + :returns: The updated CredentialInstance """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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: """ - Update the CredentialInstance + Asynchronous coroutine to update the CredentialInstance - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the CredentialInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'sandbox': payload.get('sandbox'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: """ - return self._properties['sid'] + Create the CredentialInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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 """ - 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 = 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 string that you assigned to describe the resource - :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 of push-notification service the credential is for - :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: [APN only] Whether to send the credential to sandbox APNs - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Credential 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 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 the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: The 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: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 599197a23c..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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,799 +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 the ServiceInstance - - :param unicode friendly_name: A string to describe the resource + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=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']) + :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": """ - 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.chat.v2.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 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 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: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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`. - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The SID of the Service resource to fetch + 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, + ) - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + @property + def bindings(self) -> BindingList: """ - return ServiceContext(self._version, sid=sid, ) + Access the bindings + """ + return self._proxy.bindings - def __call__(self, sid): + @property + def channels(self) -> ChannelList: """ - Constructs a ServiceContext + Access the channels + """ + return self._proxy.channels - :param sid: The SID of the Service resource to fetch + @property + def roles(self) -> RoleList: + """ + 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: + """ + 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.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 of the Service resource to fetch - :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 the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param unicode notifications_new_message_sound: The name of the sound to play when a new message is added to a channel - :param bool notifications_new_message_badge_count_enabled: Whether the new message badge is enabled - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param unicode notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param unicode notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of webhook events that are enabled for this Service instance - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service - :param unicode media_compatibility_message: The message to send when a media message has no text - :param unicode pre_webhook_retry_count: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :param unicode post_webhook_retry_count: The number of times calls to the `post_webhook_url` will be retried - :param bool notifications_log_enabled: Whether to log notifications + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. :returns: The updated ServiceInstance - :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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'default_service_role_sid': payload.get('default_service_role_sid'), - 'default_channel_role_sid': payload.get('default_channel_role_sid'), - 'default_channel_creator_role_sid': payload.get('default_channel_creator_role_sid'), - 'read_status_enabled': payload.get('read_status_enabled'), - 'reachability_enabled': payload.get('reachability_enabled'), - 'typing_indicator_timeout': deserialize.integer(payload.get('typing_indicator_timeout')), - 'consumption_report_interval': deserialize.integer(payload.get('consumption_report_interval')), - 'limits': payload.get('limits'), - 'pre_webhook_url': payload.get('pre_webhook_url'), - 'post_webhook_url': payload.get('post_webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'webhook_filters': payload.get('webhook_filters'), - 'pre_webhook_retry_count': deserialize.integer(payload.get('pre_webhook_retry_count')), - 'post_webhook_retry_count': deserialize.integer(payload.get('post_webhook_retry_count')), - 'notifications': payload.get('notifications'), - 'media': payload.get('media'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 service role assigned to users when they are added to the service - :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 channel role assigned to users when they are added to a channel - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The channel role assigned to a channel creator when they join a new channel - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is 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: Whether the Reachability Indicator feature is enabled for this Service instance - :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: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :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: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + headers["Accept"] = "application/json" - @property - def post_webhook_url(self): - """ - :returns: The URL for post-event webhooks - :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 HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + return ServiceInstance(self._version, payload) - @property - def webhook_filters(self): - """ - :returns: The list of webhook events that are enabled for this Service instance - :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: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :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 number of times calls to the `post_webhook_url` will be retried - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['post_webhook_retry_count'] - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :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 properties of the media that the service supports - :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 absolute URL of the Service resource - :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 absolute URLs of the Service's Channels, Roles, and Users - :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. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 fetch(self): + :returns: list that will contain up to limit results """ - Fetch the ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: The 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" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - 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): + async def 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 friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param unicode notifications_new_message_sound: The name of the sound to play when a new message is added to a channel - :param bool notifications_new_message_badge_count_enabled: Whether the new message badge is enabled - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param unicode notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param unicode notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of webhook events that are enabled for this Service instance - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service - :param unicode media_compatibility_message: The message to send when a media message has no text - :param unicode pre_webhook_retry_count: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :param unicode post_webhook_retry_count: The number of times calls to the `post_webhook_url` will be retried - :param bool notifications_log_enabled: Whether to log notifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + :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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :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 c4a891db7a..125f4b9368 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -1,438 +1,536 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the Binding resource is associated with + 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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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']) + :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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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 """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 of the resource to fetch +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 of the resource to fetch + # 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 SID of the Service that the Binding resource is associated with - :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({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> BindingInstance: """ - Build an instance of BindingInstance + Fetch the BindingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + :returns: The fetched BindingInstance """ - return BindingInstance(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 BindingContext(InstanceContext): - """ """ + return BindingInstance( + 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) -> BindingInstance: """ - Initialize the BindingContext + Asynchronous coroutine to fetch the BindingInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the resource to fetch - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + :returns: The fetched BindingInstance """ - super(BindingContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the BindingInstance + headers["Accept"] = "application/json" - :returns: The fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=self._uri, ) + 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, 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 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'endpoint': payload.get('endpoint'), - 'identity': payload.get('identity'), - 'credential_sid': payload.get('credential_sid'), - 'binding_type': payload.get('binding_type'), - 'message_types': payload.get('message_types'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the Binding resource is associated with - :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 ISO 8601 date and time in GMT when the resource was 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, + 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - 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 unique endpoint identifier for the Binding - :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 string that identifies the resource's User - :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 SID of the Credential for the binding - :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 push technology to use for the binding - :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 Programmable Chat message types the binding is subscribed to - :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 absolute URL of the Binding resource - :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 absolute URLs of the Binding's User - :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 the BindingInstance + Constructs a BindingContext - :returns: The 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 b26a553f15..36d08a3896 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -1,17 +1,24 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -19,648 +26,937 @@ from twilio.rest.chat.v2.service.channel.webhook import WebhookList -class ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the ChannelList + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - 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, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "ChannelContext": """ - Create the ChannelInstance - - :param unicode friendly_name: A string to describe the new resource - :param unicode unique_name: An application-defined string that uniquely identifies the Channel resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param ChannelInstance.ChannelType type: The visibility of the channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: ChannelContext for this 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, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) - - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, type=values.unset, limit=None, page_size=None): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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. + Deletes the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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 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 """ - 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']) + 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 visibility of the channel to read - :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 visibility of the channel to read - :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance - :param 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 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: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ChannelPage(self._version, response, self._solution) + 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`. - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext - - :param sid: The SID of the resource + 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: + """ + 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 + Access the members + """ + return self._proxy.members - :param sid: The SID of the resource + @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: + """ + Access the webhooks """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + 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 SID of the Service that the resource is associated with + 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 - - def get_instance(self, payload): - """ - Build an instance of ChannelInstance + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the ChannelInstance - def __repr__(self): - """ - Provide a friendly representation + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Machine friendly representation - :rtype: str + :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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, sid): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the ChannelContext + Asynchronous coroutine that deletes the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the resource + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: True if delete succeeds, False otherwise """ - super(ChannelContext, self).__init__(version) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._members = None - self._messages = None - self._invites = None - self._webhooks = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ChannelInstance: """ Fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def fetch_async(self) -> ChannelInstance: """ - Deletes the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: The fetched ChannelInstance """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset, - x_twilio_webhook_enabled=values.unset): + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: """ Update the ChannelInstance - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. :returns: The updated ChannelInstance - :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 = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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'], + 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): - """ - Access the invites - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList - """ - if self._invites is None: - self._invites = InviteList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._invites - - @property - def webhooks(self): + def webhooks(self) -> WebhookList: """ Access the webhooks - - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList """ 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._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) - + 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" - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" - - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'attributes': payload.get('attributes'), - 'type': payload.get('type'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('created_by'), - 'members_count': deserialize.integer(payload.get('members_count')), - 'messages_count': deserialize.integer(payload.get('messages_count')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] +class ChannelList(ListResource): - @property - def unique_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + Initialize the ChannelList - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :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 visibility of the channel. Can be: `public` or `private` - :rtype: ChannelInstance.ChannelType - """ - return self._properties['type'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + # 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: """ - return self._properties['date_created'] + Create the ChannelInstance - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + :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`. - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['created_by'] - @property - def members_count(self): - """ - :returns: The number of Members in the Channel - :rtype: unicode - """ - return self._properties['members_count'] + 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 messages_count(self): - """ - :returns: The number of Messages that have been passed in the Channel - :rtype: unicode + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance """ - return self._properties['messages_count'] - @property - def url(self): + 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 absolute URL of the Channel resource - :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['url'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def links(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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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['links'] + 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 fetch(self): + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: """ - Fetch the 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. - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :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._proxy.fetch() + 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. - def delete(self, x_twilio_webhook_enabled=values.unset): + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Deletes the ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of ChannelInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - 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, - x_twilio_webhook_enabled=values.unset): + 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: """ - Update the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: The 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def members(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 ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: """ - Access the members + 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: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :returns: Page of ChannelInstance """ - return self._proxy.members + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the messages + 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: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + :returns: Page of ChannelInstance """ - return self._proxy.messages + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def invites(self): + def get(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 + ) - @property - def webhooks(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the webhooks + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + :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.webhooks + 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 b39cc0fb05..7c7f9f6211 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -1,448 +1,598 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[InviteContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + :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 the InviteInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + return self._proxy.delete() - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) - 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` value of the resources to read - :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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The SID of the Invite resource to fetch - :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 of the Invite resource to fetch - :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 + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + def __repr__(self) -> str: """ - super(InvitePage, 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 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The SID of the Invite resource to fetch + :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 the InviteInstance + Create the InviteInstance - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: """ - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'created_by': payload.get('created_by'), - 'url': payload.get('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): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Channel the new resource belongs to - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 SID of the Role assigned to the member - :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 identity of the User that created the invite - :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 absolute URL of the Invite resource - :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 the InviteInstance + Constructs a InviteContext - :returns: The 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 8c7678afd4..f07cb21891 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -1,563 +1,905 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MemberList + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel for the member + """ + :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 - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + @property + def _proxy(self) -> "MemberContext": """ - super(MemberList, 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, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Members'.format(**self._solution) + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - def 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Create the MemberInstance + Deletes the MemberInstance - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last Message in the Channel the Member has read - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: The created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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, }) + Asynchronous coroutine that deletes the MemberInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return MemberInstance( - 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( + 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` value of the resources to read - :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']) - 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() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :param unicode identity: The `identity` value of the resources to read - :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 + :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + 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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - 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[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The SID of the Member resource to fetch + :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( + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - 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 of the Member resource to fetch - :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 = 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, + 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: """ - Provide a friendly representation + Update the MemberInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + 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({}) -class MemberPage(Page): - """ """ + 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"], + ) - def __init__(self, version, response, solution): + 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 """ - Initialize the MemberPage - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel for the member + 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" - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: """ - super(MemberPage, 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 MemberPage(Page): - def get_instance(self, payload): + 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the channel the member belongs to - :param sid: The SID of the Member resource to fetch + :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): + 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: """ - Fetch the MemberInstance + Create the MemberInstance - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) return MemberInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the MemberInstance - - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The created MemberInstance """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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", + } + ) - 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): - """ - Update the MemberInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the Member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + headers["Accept"] = "application/json" - :returns: The 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), - 'Attributes': attributes, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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): - """ """ + 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. - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + :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) - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload.get('last_consumption_timestamp')), - 'url': payload.get('url'), - 'attributes': payload.get('attributes'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - # 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, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext - """ - 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'], + :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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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): - """ - :returns: The SID of the Channel for the member - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the member - :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 index of the last Message that the Member has read within the Channel - :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 ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel - :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: The absolute URL of the Member resource - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['url'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers = values.of({"Content-Type": "application/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 fetch(self): + def get_page(self, target_url: str) -> MemberPage: """ - Fetch the MemberInstance + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> MemberPage: """ - Deletes the MemberInstance + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of MemberInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): + def get(self, sid: str) -> MemberContext: """ - Update the MemberInstance + Constructs a MemberContext - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the Member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :returns: The updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + def __call__(self, sid: str) -> MemberContext: """ - 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, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + Constructs a MemberContext + + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + 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 a6609311b4..d0bf2e5ac7 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -1,600 +1,905 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MessageList + class OrderType(object): + ASC = "asc" + DESC = "desc" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList - """ - super(MessageList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None - 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, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "MessageContext": """ - Create the MessageInstance + 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 from_: The Identity of the new message's author - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message - :param unicode body: The message to send to the channel - :param unicode media_sid: The Media Sid to be attached to the new Message - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: The created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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, }) + Deletes the MessageInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, order=values.unset, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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. + Asynchronous coroutine that deletes the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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 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.message.MessageInstance] + :returns: True if delete succeeds, False otherwise """ - 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']) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, order=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.channel.message.MessageInstance] + :returns: The fetched MessageInstance """ - return list(self.stream(order=order, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "MessageInstance": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.chat.v2.service.channel.message.MessagePage + :returns: The fetched MessageInstance """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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. - return MessagePage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: The updated MessageInstance """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + 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_, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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_, ) - return MessagePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a MessageContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The SID of the Message resource to fetch +class MessageContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Message resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Message resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) ) - def __call__(self, sid): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MessageContext + Deletes the MessageInstance - :param sid: The SID of the Message resource to fetch + :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, + } ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MessageInstance - :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 MessagePage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> MessageInstance: """ - Initialize the MessagePage + Fetch the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: The fetched MessageInstance """ - super(MessagePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of MessageInstance + 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.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ 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"], + 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 MessageContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, channel_sid, sid): - """ - Initialize the MessageContext + 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the message to fetch belongs to - :param sid: The SID of the Message resource to fetch + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + 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: """ - super(MessageContext, self).__init__(version) + Update the MessageInstance - # 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) + :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. - def fetch(self): + :returns: The updated MessageInstance """ - Fetch the MessageInstance - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=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 """ - Deletes the MessageInstance - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + 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 - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, from_=values.unset, - x_twilio_webhook_enabled=values.unset): - """ - Update the MessageInstance + headers["Accept"] = "application/json" - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable - :param unicode from_: The Identity of the message's author - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + 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: """ - 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({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + Provide a friendly representation - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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, - 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 __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 MessageInstance(InstanceResource): - """ """ +class MessageList(ListResource): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + :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`. - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'attributes': payload.get('attributes'), - 'service_sid': payload.get('service_sid'), - 'to': payload.get('to'), - 'channel_sid': payload.get('channel_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'last_updated_by': payload.get('last_updated_by'), - 'was_edited': payload.get('was_edited'), - 'from_': payload.get('from'), - 'body': payload.get('body'), - 'index': deserialize.integer(payload.get('index')), - 'type': payload.get('type'), - 'media': payload.get('media'), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the MessageInstance - :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'], - ) - return self._context + :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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + 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", + } + ) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers["Accept"] = "application/json" - @property - def to(self): - """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode - """ - return self._properties['to'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the Message resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + 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. - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + :returns: The created MessageInstance """ - return self._properties['date_updated'] - @property - def last_updated_by(self): - """ - :returns: The Identity of the User who last updated the Message - :rtype: unicode - """ - return self._properties['last_updated_by'] + 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", + } + ) - @property - def was_edited(self): - """ - :returns: Whether the message has been edited since it was created - :rtype: bool - """ - return self._properties['was_edited'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def from_(self): - """ - :returns: The Identity of the message's author - :rtype: unicode - """ - return self._properties['from_'] + headers["Accept"] = "application/json" - @property - def body(self): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - :returns: The content of the message - :rtype: unicode + 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 """ - return self._properties['body'] + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) - @property - def index(self): + 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]: """ - :returns: The index of the message within the Channel - :rtype: unicode + 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 """ - return self._properties['index'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) - @property - def type(self): + 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]: """ - :returns: The Message type - :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 "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]: """ - return self._properties['type'] + 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 media(self): + :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: """ - :returns: A Media object that describes the Message's media if attached; otherwise, null - :rtype: dict + 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 """ - return self._properties['media'] + data = values.of( + { + "Order": order, + "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 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: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + 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 """ - return self._properties['url'] + 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 fetch(self): + def get_page(self, target_url: str) -> MessagePage: """ - Fetch the MessageInstance + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.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 delete(self, x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> MessagePage: """ - Deletes the MessageInstance + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of MessageInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, from_=values.unset, - x_twilio_webhook_enabled=values.unset): + def get(self, sid: str) -> MessageContext: """ - Update the MessageInstance + Constructs a MessageContext - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable - :param unicode from_: The Identity of the message's author - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + def __call__(self, sid: str) -> MessageContext: """ - return self._proxy.update( - body=body, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - last_updated_by=last_updated_by, - from_=from_, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + Constructs a MessageContext + + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + 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 index 41888953d2..3e31df4288 100644 --- a/twilio/rest/chat/v2/service/channel/webhook.py +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -1,524 +1,800 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 WebhookList(ListResource): - """ """ +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") + ) - 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[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": """ - Initialize the WebhookList + 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 SID of the Service that the Channel Webhook resource is associated with - :param channel_sid: The SID of the Channel the Channel Webhook resource belongs to + :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 - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + def delete(self) -> bool: """ - super(WebhookList, self).__init__(version) + Deletes the WebhookInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 WebhookInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.webhook.WebhookInstance] + + :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) -> "WebhookInstance": + """ + Fetch the WebhookInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.webhook.WebhookInstance] + + :returns: The fetched WebhookInstance """ - 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, + 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": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + Update the WebhookInstance - :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 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: Page of WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: The updated WebhookInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + 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, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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. - return WebhookPage(self._version, response, self._solution) + :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 get_page(self, target_url): + def __repr__(self) -> str: """ - Retrieve a specific page of WebhookInstance 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 WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + +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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the WebhookInstance + - def create(self, type, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the WebhookInstance - :param WebhookInstance.Type type: The type of webhook - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + headers = values.of({}) - :returns: The created WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + 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 """ - 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, - }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> WebhookInstance: """ - Constructs a WebhookContext + Asynchronous coroutine to fetch the WebhookInstance - :param sid: The SID of the Channel Webhook resource to fetch - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :returns: The fetched WebhookInstance """ - return WebhookContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( 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): + 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: """ - Constructs a WebhookContext + Update the WebhookInstance - :param sid: The SID of the Channel Webhook resource to fetch + :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: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :returns: The updated WebhookInstance """ - return WebhookContext( + + 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, - 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): - """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :returns: The updated WebhookInstance """ - return '' + 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({}) -class WebhookPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the WebhookPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Channel Webhook resource is associated with - :param channel_sid: The SID of the Channel the Channel Webhook resource belongs to + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookPage - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: Machine friendly representation """ - super(WebhookPage, 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 WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: """ Build an instance of WebhookInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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'], + 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 WebhookContext(InstanceContext): - """ """ +class WebhookList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the WebhookContext + Initialize the WebhookList - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service with the Channel to fetch the Webhook resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The SID of the Channel Webhook resource to fetch + :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`. - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext """ - super(WebhookContext, 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}/Webhooks/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) - def fetch(self): + 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: """ - Fetch the WebhookInstance + Create the WebhookInstance - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + 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 """ - Update the WebhookInstance - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + 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"}) - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the WebhookInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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. - def __repr__(self): - """ - Provide a friendly representation + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class WebhookInstance(InstanceResource): - """ """ - - class Type(object): - WEBHOOK = "webhook" - TRIGGER = "trigger" - STUDIO = "studio" + 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. - class Method(object): - GET = "GET" - POST = "POST" + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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): + :returns: Generator that will yield up to limit results """ - Initialize the WebhookInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - super(WebhookInstance, self).__init__(version) + Lists WebhookInstance 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'type': payload.get('type'), - 'url': payload.get('url'), - 'configuration': payload.get('configuration'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 = { - 'service_sid': service_sid, - 'channel_sid': channel_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[WebhookInstance]: """ - 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 WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_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 unique string that identifies the resource - :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, + ) -> WebhookPage: """ - return self._properties['sid'] + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 service_sid(self): - """ - :returns: The SID of the Service that the Channel Webhook resource is associated with - :rtype: unicode + :returns: Page of WebhookInstance """ - return self._properties['service_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the Channel Webhook resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def type(self): - """ - :returns: The type of webhook - :rtype: unicode - """ - return self._properties['type'] + headers["Accept"] = "application/json" - @property - def url(self): - """ - :returns: The absolute URL of the Channel Webhook resource - :rtype: unicode - """ - return self._properties['url'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) - @property - def configuration(self): - """ - :returns: The JSON string that describes the configuration object for the channel webhook - :rtype: dict + async def 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: """ - return self._properties['configuration'] + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the 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: Page of WebhookInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: """ - return self._properties['date_updated'] + 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 - def fetch(self): + :returns: Page of WebhookInstance """ - Fetch the WebhookInstance + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + async def get_page_async(self, target_url: str) -> WebhookPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance """ - Update the WebhookInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param sid: The SID of the Channel Webhook resource to update. """ - 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, + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def delete(self): + def __call__(self, sid: str) -> WebhookContext: """ - Deletes the WebhookInstance + Constructs a WebhookContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Channel Webhook resource to update. """ - return self._proxy.delete() + return WebhookContext( + 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/role.py b/twilio/rest/chat/v2/service/role.py index a245906337..fef06436d0 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -1,442 +1,645 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the RoleList +class RoleInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList - """ - super(RoleList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None - def create(self, friendly_name, type, permission): + @property + def _proxy(self) -> "RoleContext": """ - Create the RoleInstance - - :param unicode friendly_name: A string to describe the new resource - :param RoleInstance.RoleType type: The type of role - :param unicode permission: A permission the role should have + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: RoleContext for this RoleInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the RoleInstance - :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.role.RoleInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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 that deletes 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: 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) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The fetched RoleInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RolePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RoleInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The fetched RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RolePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Update the RoleInstance - :param sid: The SID of the Role resource to fetch + :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: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update( + permission=permission, + ) - def __call__(self, sid): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance - :param sid: The SID of the Role resource to fetch + :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: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + permission=permission, + ) - 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 RolePage(Page): - """ """ +class RoleContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the RolePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the RoleContext - :returns: twilio.rest.chat.v2.service.role.RolePage - :rtype: twilio.rest.chat.v2.service.role.RolePage + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Role resource in. + :param sid: The SID of the Role resource to update. """ - super(RolePage, 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}/Roles/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RoleInstance + Deletes 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: True if delete succeeds, False otherwise """ - return RoleInstance(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 RoleInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RoleContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> RoleInstance: """ - Initialize the RoleContext + Fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the Role resource to fetch - :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 = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: """ - Fetch the RoleInstance + Asynchronous coroutine to fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=self._uri, ) - def update(self, permission): + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Update the RoleInstance + Asynchronous coroutine to update the RoleInstance - :param unicode permission: A permission the role should have + :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 - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'permissions': payload.get('permissions'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 string that you assigned to describe the resource - :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 of role - :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: An array of the permissions the role has been granted - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Role 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance """ - Fetch the RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: The 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: A permission the role should have + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: The 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 d0ab436294..9fbde6feda 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -1,563 +1,804 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the UserList +class UserInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList - """ - super(UserList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "UserContext": """ - Create the UserInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the new resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: UserContext for this 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, }) + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete(self) -> bool: + """ + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - 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) - - def get(self, sid): + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance - :param sid: The SID of the User resource to fetch + :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.UserContext - :rtype: twilio.rest.chat.v2.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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def user_bindings(self) -> UserBindingList: """ - Constructs a UserContext - - :param sid: The SID of the User resource to fetch + Access the user_bindings + """ + return self._proxy.user_bindings - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + @property + def user_channels(self) -> UserChannelList: + """ + 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 SID of the Service that the resource is associated with + 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 - - def get_instance(self, payload): - """ - Build an instance of UserInstance + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance - 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 UserContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the UserContext + Asynchronous coroutine that deletes the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the User resource to fetch - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: True if delete succeeds, False otherwise """ - 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 + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> UserInstance: """ Fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> UserInstance: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched UserInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ Update the UserInstance - :param unicode role_sid: The SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 - :rtype: twilio.rest.chat.v2.service.user.UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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): - """ """ - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'attributes': payload.get('attributes'), - 'friendly_name': payload.get('friendly_name'), - 'role_sid': payload.get('role_sid'), - 'identity': payload.get('identity'), - 'is_online': payload.get('is_online'), - 'is_notifiable': payload.get('is_notifiable'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'joined_channels_count': deserialize.integer(payload.get('joined_channels_count')), - 'links': payload.get('links'), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the user - :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 string that identifies the resource's User - :rtype: unicode """ - return self._properties['identity'] + super().__init__(version) - @property - def is_online(self): - """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + # 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: """ - return self._properties['is_online'] + 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/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 """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance """ - return self._properties['is_notifiable'] - @property - def date_created(self): + 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 number of Channels the User is a Member of - :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 absolute URLs of the Channel and Binding resources related to the user - :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 absolute URL of the User resource - :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"}) - def fetch(self): + 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: """ - Fetch the UserInstance + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately - :returns: The 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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) - def delete(self): + 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, x_twilio_webhook_enabled=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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, - ) + 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 468adfe399..8d79c551af 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -1,450 +1,552 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with - :param user_sid: The SID of the User with the binding + 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 push technology used by the User Binding resources to read - :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']) + :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 push technology used by the User Binding resources to read - :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 push technology used by the User Binding resources to read - :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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 of the User Binding resource to fetch + 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 of the User Binding resource to fetch - :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 SID of the Service that the resource is associated with - :param user_sid: The SID of the User with the binding - :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 SID of the Service to fetch the resource from - :param user_sid: The SID of the User with the binding - :param sid: The SID of the User Binding resource to fetch + 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 the UserBindingInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'endpoint': payload.get('endpoint'), - 'identity': payload.get('identity'), - 'user_sid': payload.get('user_sid'), - 'credential_sid': payload.get('credential_sid'), - 'binding_type': payload.get('binding_type'), - 'message_types': payload.get('message_types'), - 'url': payload.get('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. - # Context - self._context = None + """ + super().__init__(version) + + # 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 unique string that identifies the resource - :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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + 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]: """ - 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 unique endpoint identifier for the User Binding - :rtype: unicode - """ - return self._properties['endpoint'] + return self._version.stream_async(page, limits["limit"]) - @property - def identity(self): - """ - :returns: The string that identifies the resource's User - :rtype: unicode + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - 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 SID of the User with the binding - :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 SID of the Credential for the binding - :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 push technology to use for the binding - :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 Programmable Chat message types the binding is subscribed to - :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 absolute URL of the User Binding resource - :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 the UserBindingInstance + Constructs a UserBindingContext - :returns: The 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 ff58a2344f..9fab357368 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -1,485 +1,708 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 UserChannelList(ListResource): - """ """ +class UserChannelInstance(InstanceResource): - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserChannelList + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - """ - super(UserChannelList, self).__init__(version) + 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") + ) - # 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, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "UserChannelContext": """ - 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. + 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: 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the UserChannelInstance - page = self.page(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']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Lists UserChannelInstance 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 UserChannelInstance - :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.user.user_channel.UserChannelInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream(limit=limit, page_size=page_size, )) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "UserChannelInstance": """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The fetched UserChannelInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return UserChannelPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "UserChannelInstance": """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserChannelInstance - :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 + :returns: The fetched UserChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return UserChannelPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a UserChannelContext + Update the UserChannelInstance - :param channel_sid: The SID of the Channel that has the User Channel to fetch + :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: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: The updated UserChannelInstance """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - def __call__(self, 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": """ - Constructs a UserChannelContext + Asynchronous coroutine to update the UserChannelInstance - :param channel_sid: The SID of the Channel that has the User Channel to fetch + :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: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: The updated UserChannelInstance """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - def __repr__(self): + 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 UserChannelPage(Page): - """ """ +class UserChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): """ - Initialize the UserChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + Initialize the UserChannelContext - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :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(UserChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) + ) - def get_instance(self, payload): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Build an instance of UserChannelInstance + Deletes the UserChannelInstance - :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.user.user_channel.UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :returns: True if delete succeeds, False otherwise """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({}) - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class UserChannelContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, user_sid, channel_sid): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the UserChannelContext + Asynchronous coroutine that deletes the UserChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the User Channel resource from - :param user_sid: The SID of the User to fetch the User Channel resource from - :param channel_sid: The SID of the Channel that has the User Channel to fetch + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: True if delete succeeds, False otherwise """ - super(UserChannelContext, self).__init__(version) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # 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) + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> UserChannelInstance: """ Fetch the UserChannelInstance + :returns: The fetched UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def fetch_async(self) -> UserChannelInstance: """ - Deletes the UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched UserChannelInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: """ Update the UserChannelInstance - :param UserChannelInstance.NotificationLevel notification_level: The push notification level to assign to the User Channel - :param unicode last_consumed_message_index: The index of the last Message that the Member has read within the Channel - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel + :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 - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ - data = values.of({ - 'NotificationLevel': notification_level, - 'LastConsumedMessageIndex': last_consumed_message_index, - 'LastConsumptionTimestamp': serialize.iso8601_datetime(last_consumption_timestamp), - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + 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: """ - Provide a friendly representation + Asynchronous coroutine to update the UserChannelInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) -class UserChannelInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + headers["Accept"] = "application/json" - class NotificationLevel(object): - DEFAULT = "default" - MUTED = "muted" + 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 __init__(self, version, payload, service_sid, user_sid, channel_sid=None): + 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) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'user_sid': payload.get('user_sid'), - 'member_sid': payload.get('member_sid'), - 'status': payload.get('status'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'unread_messages_count': deserialize.integer(payload.get('unread_messages_count')), - 'links': payload.get('links'), - 'url': payload.get('url'), - 'notification_level': payload.get('notification_level'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'channel_sid': channel_sid or self._properties['channel_sid'], - } +class UserChannelPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ - 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 UserChannelInstance - :returns: UserChannelContext for this UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :param payload: Payload response from the API """ - 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 + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['service_sid'] + return "" - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] - @property - def user_sid(self): - """ - :returns: The SID of the User the User Channel belongs to - :rtype: unicode +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - return self._properties['user_sid'] + 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. - @property - def member_sid(self): """ - :returns: The SID of the User as a Member in the Channel - :rtype: unicode + 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]: """ - return self._properties['member_sid'] + 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 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 of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["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['status'] + 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 last_consumed_message_index(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 index of the last Message in the Channel the Member has read - :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[UserChannelInstance]: """ - return self._properties['last_consumed_message_index'] + 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 unread_messages_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 number of unread Messages in the Channel for the User - :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['unread_messages_count'] + 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 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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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, + ) -> UserChannelPage: """ - return self._properties['links'] + Retrieve a single page of UserChannelInstance 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 UserChannelInstance """ - :returns: The absolute URL of the 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 = 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['url'] + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - @property - def notification_level(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 push notification level of the User for the Channel - :rtype: UserChannelInstance.NotificationLevel + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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['notification_level'] + 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 - def fetch(self): + :returns: Page of UserChannelInstance """ - Fetch the UserChannelInstance + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - :returns: The fetched UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of UserChannelInstance 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 UserChannelInstance """ - Deletes the UserChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, channel_sid: str) -> UserChannelContext: """ - return self._proxy.delete() + Constructs a UserChannelContext - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + :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`. """ - Update the UserChannelInstance + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - :param UserChannelInstance.NotificationLevel notification_level: The push notification level to assign to the User Channel - :param unicode last_consumed_message_index: The index of the last Message that the Member has read within the Channel - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext - :returns: The updated UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :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._proxy.update( - notification_level=notification_level, - last_consumed_message_index=last_consumed_message_index, - last_consumption_timestamp=last_consumption_timestamp, + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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 index 3abba93bb2..d60cb426ae 100644 --- a/twilio/rest/conversations/__init__.py +++ b/twilio/rest/conversations/__init__.py @@ -1,60 +1,87 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.conversations.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Conversations Domain - - :returns: Domain for Conversations - :rtype: twilio.rest.conversations.Conversations - """ - super(Conversations, self).__init__(twilio) +class Conversations(ConversationsBase): + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration - self.base_url = 'https://conversations.twilio.com' + @property + def address_configurations(self) -> AddressConfigurationList: + warn( + "address_configurations is deprecated. Use v1.address_configurations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.address_configurations - # Versions - self._v1 = None + @property + def conversations(self) -> ConversationList: + warn( + "conversations is deprecated. Use v1.conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.conversations @property - def v1(self): - """ - :returns: Version v1 of conversations - :rtype: twilio.rest.conversations.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials @property - def conversations(self): - """ - :rtype: twilio.rest.conversations.v1.conversation.ConversationList - """ - return self.v1.conversations + 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 webhooks(self): - """ - :rtype: twilio.rest.conversations.v1.webhook.WebhookList - """ - return self.v1.webhooks + def roles(self) -> RoleList: + warn( + "roles is deprecated. Use v1.roles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.roles - 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 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 index 9863a22dc9..1ec6c22a7b 100644 --- a/twilio/rest/conversations/v1/__init__.py +++ b/twilio/rest/conversations/v1/__init__.py @@ -1,53 +1,115 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.webhook import WebhookList +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Conversations - :returns: V1 version of Conversations - :rtype: twilio.rest.conversations.v1.V1.V1 + :param domain: The Twilio.conversations domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._conversations = None - self._webhooks = None + 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 conversations(self): - """ - :rtype: twilio.rest.conversations.v1.conversation.ConversationList - """ + 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 webhooks(self): - """ - :rtype: twilio.rest.conversations.v1.webhook.WebhookList - """ - if self._webhooks is None: - self._webhooks = WebhookList(self) - return self._webhooks + def conversation_with_participants(self) -> ConversationWithParticipantsList: + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self + ) + return self._conversation_with_participants - def __repr__(self): + @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 - :rtype: str """ - return '' + 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 index 7f7170091a..d1f08cc2d8 100644 --- a/twilio/rest/conversations/v1/conversation/__init__.py +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -1,601 +1,1025 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.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 ConversationList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ConversationInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the ConversationList + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" - :param Version version: Version that contains the resource + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.conversations.v1.conversation.ConversationList - :rtype: twilio.rest.conversations.v1.conversation.ConversationList - """ - super(ConversationList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Conversations'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None - def create(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, messaging_service_sid=values.unset, - attributes=values.unset, state=values.unset, - timers_inactive=values.unset, timers_closed=values.unset, - x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "ConversationContext": """ - Create the ConversationInstance - - :param unicode friendly_name: The human-readable name of this conversation. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode messaging_service_sid: The unique id of the SMS Service this conversation belongs to. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param ConversationInstance.State state: Current state of this conversation. - :param unicode timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. - :param unicode timers_closed: ISO8601 duration when conversation will be switched to `closed` state. - :param ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + :returns: ConversationContext for this ConversationInstance """ - data = values.of({ - 'FriendlyName': friendly_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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + if self._context is None: + self._context = ConversationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance - return ConversationInstance(self._version, payload, ) + :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 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 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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.conversations.v1.conversation.ConversationInstance] + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ConversationInstance - page = self.page(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']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the ConversationInstance - :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.conversations.v1.conversation.ConversationInstance] + :returns: The fetched ConversationInstance """ - 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) -> "ConversationInstance": """ - Retrieve a single page of ConversationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ConversationInstance - :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 ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: The fetched ConversationInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return ConversationPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated ConversationInstance """ - Retrieve a specific page of ConversationInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: The updated ConversationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ConversationPage(self._version, response, self._solution) + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages - def get(self, sid): + @property + def participants(self) -> ParticipantList: """ - Constructs a ConversationContext + Access the participants + """ + return self._proxy.participants - :param sid: A 34 character string that uniquely identifies this resource. + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks - :returns: twilio.rest.conversations.v1.conversation.ConversationContext - :rtype: twilio.rest.conversations.v1.conversation.ConversationContext + def __repr__(self) -> str: """ - return ConversationContext(self._version, sid=sid, ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a ConversationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.ConversationContext - :rtype: twilio.rest.conversations.v1.conversation.ConversationContext - """ - return ConversationContext(self._version, sid=sid, ) +class ConversationContext(InstanceContext): - def __repr__(self): + def __init__(self, version: Version, sid: str): """ - Provide a friendly representation + Initialize the ConversationContext - :returns: Machine friendly representation - :rtype: str + :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. """ - return '' + super().__init__(version) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".format(**self._solution) -class ConversationPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None - def __init__(self, version, response, solution): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the ConversationPage + Deletes the ConversationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.conversations.v1.conversation.ConversationPage - :rtype: twilio.rest.conversations.v1.conversation.ConversationPage + :returns: True if delete succeeds, False otherwise """ - super(ConversationPage, self).__init__(version, response) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): + 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: """ - Build an instance of ConversationInstance + Asynchronous coroutine that deletes the ConversationInstance - :param dict payload: Payload response from the API + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.conversations.v1.conversation.ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + :returns: True if delete succeeds, False otherwise """ - return ConversationInstance(self._version, payload, ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: """ - Provide a friendly representation + Fetch the ConversationInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ConversationInstance """ - return '' + headers = values.of({}) -class ConversationContext(InstanceContext): - """ 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 ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> ConversationInstance: """ - Initialize the ConversationContext + Asynchronous coroutine to fetch the ConversationInstance - :param Version version: Version that contains the resource - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.ConversationContext - :rtype: twilio.rest.conversations.v1.conversation.ConversationContext + :returns: The fetched ConversationInstance """ - super(ConversationContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Conversations/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._participants = None - self._messages = None - self._webhooks = None + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def update(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, attributes=values.unset, - messaging_service_sid=values.unset, state=values.unset, - timers_inactive=values.unset, timers_closed=values.unset, - x_twilio_webhook_enabled=values.unset): + 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 unicode friendly_name: The human-readable name of this conversation. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param unicode messaging_service_sid: The unique id of the SMS Service this conversation belongs to. - :param ConversationInstance.State state: Current state of this conversation. - :param unicode timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. - :param unicode timers_closed: ISO8601 duration when conversation will be switched to `closed` state. - :param ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 - :rtype: twilio.rest.conversations.v1.conversation.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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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({}) - return ConversationInstance(self._version, payload, sid=self._solution['sid'], ) + 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 - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the ConversationInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return self._version.delete(method='DELETE', uri=self._uri, 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. - def fetch(self): + :returns: The updated ConversationInstance """ - Fetch the ConversationInstance - :returns: The fetched ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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({}) - return ConversationInstance(self._version, payload, sid=self._solution['sid'], ) + 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 - @property - def participants(self): - """ - Access the participants + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList - """ - if self._participants is None: - self._participants = ParticipantList(self._version, conversation_sid=self._solution['sid'], ) - return self._participants + 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): + def messages(self) -> MessageList: """ Access the messages - - :returns: twilio.rest.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList """ if self._messages is None: - self._messages = MessageList(self._version, conversation_sid=self._solution['sid'], ) + self._messages = MessageList( + self._version, + self._solution["sid"], + ) return self._messages @property - def webhooks(self): + def participants(self) -> ParticipantList: """ - Access the webhooks + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks """ if self._webhooks is None: - self._webhooks = WebhookList(self._version, conversation_sid=self._solution['sid'], ) + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) 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 ConversationInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - class State(object): - INACTIVE = "inactive" - ACTIVE = "active" - CLOSED = "closed" - def __init__(self, version, payload, sid=None): - """ - Initialize the ConversationInstance - - :returns: twilio.rest.conversations.v1.conversation.ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance - """ - super(ConversationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'chat_service_sid': payload.get('chat_service_sid'), - 'messaging_service_sid': payload.get('messaging_service_sid'), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'attributes': payload.get('attributes'), - 'state': payload.get('state'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'timers': payload.get('timers'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ConversationPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: """ - 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 ConversationInstance - :returns: ConversationContext for this ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ConversationContext(self._version, sid=self._solution['sid'], ) - return self._context + return ConversationInstance(self._version, payload) - @property - def account_sid(self): - """ - :returns: The unique id of the Account responsible for this conversation. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def chat_service_sid(self): - """ - :returns: The unique id of the Chat Service this conversation belongs to. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['chat_service_sid'] + return "" - @property - def messaging_service_sid(self): - """ - :returns: The unique id of the SMS Service this conversation belongs to. - :rtype: unicode - """ - return self._properties['messaging_service_sid'] - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] +class ConversationList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version): """ - :returns: The human-readable name of this conversation. - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the ConversationList - @property - def attributes(self): - """ - :returns: An optional string metadata field you can use to store any data you wish. - :rtype: unicode - """ - return self._properties['attributes'] + :param version: Version that contains the resource - @property - def state(self): - """ - :returns: Current state of this conversation. - :rtype: ConversationInstance.State """ - return self._properties['state'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The date that this resource was created. - :rtype: datetime + 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: """ - return self._properties['date_created'] + Create the ConversationInstance - @property - def date_updated(self): + :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 """ - :returns: The date that this resource was last updated. - :rtype: datetime + + 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 """ - return self._properties['date_updated'] - @property - def timers(self): + 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]: """ - :returns: Timer date values for this conversation. - :rtype: dict + 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 """ - return self._properties['timers'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: An absolute URL for this conversation. - :rtype: unicode + 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 """ - return self._properties['url'] + 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"], + ) - @property - def links(self): + 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]: """ - :returns: Absolute URLs to access the Participants of this Conversation. - :rtype: unicode + 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]: """ - return self._properties['links'] + 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. - def update(self, friendly_name=values.unset, date_created=values.unset, - date_updated=values.unset, attributes=values.unset, - messaging_service_sid=values.unset, state=values.unset, - timers_inactive=values.unset, timers_closed=values.unset, - x_twilio_webhook_enabled=values.unset): + :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: """ - Update the ConversationInstance + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The human-readable name of this conversation. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param unicode messaging_service_sid: The unique id of the SMS Service this conversation belongs to. - :param ConversationInstance.State state: Current state of this conversation. - :param unicode timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. - :param unicode timers_closed: ISO8601 duration when conversation will be switched to `closed` state. - :param ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: The updated ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + :returns: Page of ConversationInstance """ - return self._proxy.update( - 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the ConversationInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :param ConversationInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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 """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + 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" - def fetch(self): + 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: """ - Fetch the ConversationInstance + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately - :returns: The fetched ConversationInstance - :rtype: twilio.rest.conversations.v1.conversation.ConversationInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) - @property - def participants(self): + async def get_page_async(self, target_url: str) -> ConversationPage: """ - Access the participants + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance """ - return self._proxy.participants + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) - @property - def messages(self): + def get(self, sid: str) -> ConversationContext: """ - Access the messages + Constructs a ConversationContext - :returns: twilio.rest.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. """ - return self._proxy.messages + return ConversationContext(self._version, sid=sid) - @property - def webhooks(self): + def __call__(self, sid: str) -> ConversationContext: """ - Access the webhooks + Constructs a ConversationContext - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. """ - return self._proxy.webhooks + return ConversationContext(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/conversations/v1/conversation/message/__init__.py b/twilio/rest/conversations/v1/conversation/message/__init__.py index 297bd10746..04e7fdf252 100644 --- a/twilio/rest/conversations/v1/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -1,566 +1,912 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.conversations.v1.conversation.message.delivery_receipt import DeliveryReceiptList +from twilio.rest.conversations.v1.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) -class MessageList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class MessageInstance(InstanceResource): - def __init__(self, version, conversation_sid): - """ - Initialize the MessageList + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this message. + """ + :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 - :returns: twilio.rest.conversations.v1.conversation.message.MessageList - :rtype: twilio.rest.conversations.v1.conversation.message.MessageList + @property + def _proxy(self) -> "MessageContext": """ - super(MessageList, 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 = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_sid}/Messages'.format(**self._solution) + :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 create(self, author=values.unset, body=values.unset, - date_created=values.unset, date_updated=values.unset, - attributes=values.unset, media_sid=values.unset, - x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Create the MessageInstance + Deletes the MessageInstance - :param unicode author: The channel specific identifier of the message's author. - :param unicode body: The content of the message. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: A string metadata field you can use to store any data you wish. - :param unicode media_sid: The Media Sid to be attached to the new Message. - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: The created MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Author': author, - 'Body': body, - 'DateCreated': serialize.iso8601_datetime(date_created), - 'DateUpdated': serialize.iso8601_datetime(date_updated), - 'Attributes': attributes, - 'MediaSid': media_sid, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance - return MessageInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) + :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 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 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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.conversations.v1.conversation.message.MessageInstance] + def fetch(self) -> "MessageInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the MessageInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MessageInstance - :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.conversations.v1.conversation.message.MessageInstance] + :returns: The fetched MessageInstance """ - 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): + 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": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Update the MessageInstance - :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 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: Page of MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage + :returns: The updated MessageInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + 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, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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. - return MessagePage(self._version, response, self._solution) + :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, + ) - def get_page(self, target_url): + @property + def delivery_receipts(self) -> DeliveryReceiptList: """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Access the delivery_receipts + """ + return self._proxy.delivery_receipts - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage + :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 MessagePage(self._version, response, self._solution) - def get(self, sid): +class MessageContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): """ - Constructs a MessageContext + 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. - - :returns: twilio.rest.conversations.v1.conversation.message.MessageContext - :rtype: twilio.rest.conversations.v1.conversation.message.MessageContext """ - return MessageContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + super().__init__(version) - def __call__(self, sid): - """ - Constructs a MessageContext + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) - :param sid: A 34 character string that uniquely identifies this resource. + self._delivery_receipts: Optional[DeliveryReceiptList] = None - :returns: twilio.rest.conversations.v1.conversation.message.MessageContext - :rtype: twilio.rest.conversations.v1.conversation.message.MessageContext + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - return MessageContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + Deletes the MessageInstance - def __repr__(self): - """ - Provide a friendly representation + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Machine friendly representation - :rtype: str + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + headers = values.of({}) -class MessagePage(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, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the MessagePage + Asynchronous coroutine that deletes the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param conversation_sid: The unique id of the Conversation for this message. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.conversations.v1.conversation.message.MessagePage - :rtype: twilio.rest.conversations.v1.conversation.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - super(MessagePage, self).__init__(version, response) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # 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) -> MessageInstance: """ - Build an instance of MessageInstance + Fetch the MessageInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.conversations.v1.conversation.message.MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance + :returns: The fetched MessageInstance """ - return MessageInstance(self._version, payload, conversation_sid=self._solution['conversation_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 MessageContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, conversation_sid, sid): + async def fetch_async(self) -> MessageInstance: """ - Initialize the MessageContext + Asynchronous coroutine to fetch the MessageInstance - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this message. - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.message.MessageContext - :rtype: twilio.rest.conversations.v1.conversation.message.MessageContext + :returns: The fetched MessageInstance """ - super(MessageContext, self).__init__(version) - # Path Solution - self._solution = {'conversation_sid': conversation_sid, 'sid': sid, } - self._uri = '/Conversations/{conversation_sid}/Messages/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._delivery_receipts = None + headers["Accept"] = "application/json" - def update(self, author=values.unset, body=values.unset, - date_created=values.unset, date_updated=values.unset, - attributes=values.unset, x_twilio_webhook_enabled=values.unset): + 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 unicode author: The channel specific identifier of the message's author. - :param unicode body: The content of the message. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: A string metadata field you can use to store any data you wish. - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance """ - data = values.of({ - 'Author': author, - 'Body': body, - '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, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + 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 """ - Deletes the MessageInstance - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + 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 - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): - """ - Fetch the MessageInstance + headers["Accept"] = "application/json" - :returns: The fetched MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) @property - def delivery_receipts(self): + def delivery_receipts(self) -> DeliveryReceiptList: """ Access the delivery_receipts - - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList """ if self._delivery_receipts is None: self._delivery_receipts = DeliveryReceiptList( self._version, - conversation_sid=self._solution['conversation_sid'], - message_sid=self._solution['sid'], + self._solution["conversation_sid"], + self._solution["sid"], ) return self._delivery_receipts - 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 MessageInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __init__(self, version, payload, conversation_sid, sid=None): - """ - Initialize the MessageInstance - - :returns: twilio.rest.conversations.v1.conversation.message.MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance - """ - super(MessageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'conversation_sid': payload.get('conversation_sid'), - 'sid': payload.get('sid'), - 'index': deserialize.integer(payload.get('index')), - 'author': payload.get('author'), - 'body': payload.get('body'), - 'media': payload.get('media'), - 'attributes': payload.get('attributes'), - 'participant_sid': payload.get('participant_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'delivery': payload.get('delivery'), - 'links': payload.get('links'), - } - # Context - self._context = None - self._solution = {'conversation_sid': conversation_sid, 'sid': sid or self._properties['sid'], } +class MessagePage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ - 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 MessageInstance - :returns: MessageContext for this MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = MessageContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) - @property - def account_sid(self): - """ - :returns: The unique id of the Account responsible for this message. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def conversation_sid(self): - """ - :returns: The unique id of the Conversation for this message. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['conversation_sid'] + return "" - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - @property - def index(self): - """ - :returns: The index of the message within the Conversation. - :rtype: unicode - """ - return self._properties['index'] +class MessageList(ListResource): - @property - def author(self): + def __init__(self, version: Version, conversation_sid: str): """ - :returns: The channel specific identifier of the message's author. - :rtype: unicode - """ - return self._properties['author'] + Initialize the MessageList - @property - def body(self): - """ - :returns: The content of the message. - :rtype: unicode - """ - return self._properties['body'] + :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. - @property - def media(self): - """ - :returns: An array of objects that describe the Message's media if attached, otherwise, null. - :rtype: dict """ - return self._properties['media'] + super().__init__(version) - @property - def attributes(self): - """ - :returns: A string metadata field you can use to store any data you wish. - :rtype: unicode + # 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: """ - return self._properties['attributes'] + Create the MessageInstance - @property - def participant_sid(self): + :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 """ - :returns: The unique id of messages's author participant. - :rtype: unicode + + 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 """ - return self._properties['participant_sid'] - @property - def date_created(self): + 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]: """ - :returns: The date that this resource was created. - :rtype: datetime + 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 """ - return self._properties['date_created'] + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) - @property - def date_updated(self): + 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]: """ - :returns: The date that this resource was last updated. - :rtype: datetime + 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 """ - return self._properties['date_updated'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) - @property - def url(self): + 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]: """ - :returns: An absolute URL for this message. - :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 "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]: """ - return self._properties['url'] + 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 delivery(self): + :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: """ - :returns: An object that contains the summary of delivery statuses for the message to non-chat participants. - :rtype: dict + 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 """ - return self._properties['delivery'] + data = values.of( + { + "Order": order, + "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 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: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + 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 update(self, author=values.unset, body=values.unset, - date_created=values.unset, date_updated=values.unset, - attributes=values.unset, x_twilio_webhook_enabled=values.unset): + def get_page(self, target_url: str) -> MessagePage: """ - Update the MessageInstance + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :param unicode author: The channel specific identifier of the message's author. - :param unicode body: The content of the message. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: A string metadata field you can use to store any data you wish. - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The updated MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance + :returns: Page of MessageInstance """ - return self._proxy.update( - author=author, - body=body, - date_created=date_created, - date_updated=date_updated, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, - ) + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> MessagePage: """ - Deletes the MessageInstance + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of MessageInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> MessageContext: """ - Fetch the MessageInstance + Constructs a MessageContext - :returns: The fetched MessageInstance - :rtype: twilio.rest.conversations.v1.conversation.message.MessageInstance + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.fetch() + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) - @property - def delivery_receipts(self): + def __call__(self, sid: str) -> MessageContext: """ - Access the delivery_receipts + Constructs a MessageContext - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.delivery_receipts + return MessageContext( + self._version, conversation_sid=self._solution["conversation_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/conversations/v1/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py index d030a5da7e..2ed297e059 100644 --- a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -1,411 +1,482 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 DeliveryReceiptList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DeliveryReceiptInstance(InstanceResource): - def __init__(self, version, conversation_sid, message_sid): - """ - Initialize the DeliveryReceiptList + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" - :param Version version: Version that contains the resource - :param conversation_sid: The conversation_sid - :param message_sid: The sid of the message the delivery receipt belongs to + """ + :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 - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptList + @property + def _proxy(self) -> "DeliveryReceiptContext": """ - super(DeliveryReceiptList, 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 = {'conversation_sid': conversation_sid, 'message_sid': message_sid, } - self._uri = '/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the DeliveryReceiptInstance - :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.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance] + :returns: The fetched DeliveryReceiptInstance """ - 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) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance] + 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 DeliveryReceiptInstance 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 DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptPage +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, version: Version, conversation_sid: str, message_sid: str, sid: str + ): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the DeliveryReceiptContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return DeliveryReceiptPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> DeliveryReceiptInstance: """ - Retrieve a specific page of DeliveryReceiptInstance records from the API. - Request is executed immediately + Fetch the DeliveryReceiptInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptPage + :returns: The fetched DeliveryReceiptInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return DeliveryReceiptPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a DeliveryReceiptContext + headers["Accept"] = "application/json" - :param sid: A 34 character string that uniquely identifies this resource. + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext - """ - return DeliveryReceiptContext( + return DeliveryReceiptInstance( self._version, - conversation_sid=self._solution['conversation_sid'], - message_sid=self._solution['message_sid'], - sid=sid, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> DeliveryReceiptInstance: """ - Constructs a DeliveryReceiptContext + Asynchronous coroutine to fetch the DeliveryReceiptInstance - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext + :returns: The fetched DeliveryReceiptInstance """ - return DeliveryReceiptContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeliveryReceiptInstance( self._version, - conversation_sid=self._solution['conversation_sid'], - message_sid=self._solution['message_sid'], - sid=sid, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_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 DeliveryReceiptPage(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 DeliveryReceiptPage - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param conversation_sid: The conversation_sid - :param message_sid: The sid of the message the delivery receipt belongs to - - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptPage - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptPage - """ - super(DeliveryReceiptPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: """ Build an instance of DeliveryReceiptInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.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'], + conversation_sid=self._solution["conversation_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 "" -class DeliveryReceiptContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DeliveryReceiptList(ListResource): - def __init__(self, version, conversation_sid, message_sid, sid): + def __init__(self, version: Version, conversation_sid: str, message_sid: str): """ - Initialize the DeliveryReceiptContext + Initialize the DeliveryReceiptList - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this delivery receipt. - :param message_sid: The sid of the message the delivery receipt belongs to - :param sid: A 34 character string that uniquely identifies this resource. + :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. - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext """ - super(DeliveryReceiptContext, self).__init__(version) + 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) + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: """ - Fetch the 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. - :returns: The fetched DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return DeliveryReceiptInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_sid'], - message_sid=self._solution['message_sid'], - sid=self._solution['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[DeliveryReceiptInstance]: """ - Provide a friendly representation + 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. - :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 DeliveryReceiptInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + 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. - class DeliveryStatus(object): - READ = "read" - FAILED = "failed" - DELIVERED = "delivered" - UNDELIVERED = "undelivered" - SENT = "sent" + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, conversation_sid, message_sid, sid=None): + :returns: list that will contain up to limit results """ - Initialize the DeliveryReceiptInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: """ - super(DeliveryReceiptInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'message_sid': payload.get('message_sid'), - 'conversation_sid': payload.get('conversation_sid'), - 'channel_message_sid': payload.get('channel_message_sid'), - 'participant_sid': payload.get('participant_sid'), - 'status': payload.get('status'), - 'error_code': deserialize.integer(payload.get('error_code')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'conversation_sid': conversation_sid, - 'message_sid': message_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: DeliveryReceiptContext for this DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptContext + :returns: list that will contain up to limit results """ - 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 [ + 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, + ) -> DeliveryReceiptPage: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] + Retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately - @property - def message_sid(self): - """ - :returns: The sid of the message the delivery receipt belongs to - :rtype: unicode - """ - return self._properties['message_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 conversation_sid(self): - """ - :returns: The conversation_sid - :rtype: unicode + :returns: Page of DeliveryReceiptInstance """ - return self._properties['conversation_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_message_sid(self): - """ - :returns: A messaging channel-specific identifier for the message delivered to participant - :rtype: unicode - """ - return self._properties['channel_message_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def participant_sid(self): - """ - :returns: The unique id of the participant the delivery receipt belongs to. - :rtype: unicode - """ - return self._properties['participant_sid'] + headers["Accept"] = "application/json" - @property - def status(self): - """ - :returns: The message delivery status - :rtype: DeliveryReceiptInstance.DeliveryStatus - """ - return self._properties['status'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) - @property - def error_code(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, + ) -> DeliveryReceiptPage: """ - :returns: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status - :rtype: unicode + 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 """ - return self._properties['error_code'] + 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 DeliveryReceiptPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeliveryReceiptPage: """ - :returns: The date that this resource was created. - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: """ - :returns: The date that this resource was last updated. - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> DeliveryReceiptContext: """ - :returns: An absolute URL for this delivery receipt. - :rtype: unicode + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._properties['url'] + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> DeliveryReceiptContext: """ - Fetch the DeliveryReceiptInstance + Constructs a DeliveryReceiptContext - :returns: The fetched DeliveryReceiptInstance - :rtype: twilio.rest.conversations.v1.conversation.message.delivery_receipt.DeliveryReceiptInstance + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.fetch() + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_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/conversations/v1/conversation/participant.py b/twilio/rest/conversations/v1/conversation/participant.py index 0513221e4a..deb652641a 100644 --- a/twilio/rest/conversations/v1/conversation/participant.py +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -1,530 +1,895 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ParticipantInstance(InstanceResource): - def __init__(self, version, conversation_sid): - """ - Initialize the ParticipantList + 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") - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this participant. + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantList - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantList + @property + def _proxy(self) -> "ParticipantContext": """ - super(ParticipantList, self).__init__(version) - - # Path Solution - self._solution = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_sid}/Participants'.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=values.unset, messaging_binding_address=values.unset, - messaging_binding_proxy_address=values.unset, - date_created=values.unset, date_updated=values.unset, - attributes=values.unset, - messaging_binding_projected_address=values.unset, - role_sid=values.unset, x_twilio_webhook_enabled=values.unset): + :returns: ParticipantContext for this ParticipantInstance """ - Create the ParticipantInstance + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context - :param unicode identity: A unique string identifier for the conversation participant as Chat User. - :param unicode messaging_binding_address: The address of the participant's device. - :param unicode messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param unicode messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. - :param unicode role_sid: The SID of the Role to assign to the participant - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance - :returns: The created ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.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, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return ParticipantInstance( - self._version, - payload, - conversation_sid=self._solution['conversation_sid'], + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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. + Asynchronous coroutine that deletes the ParticipantInstance - :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 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.conversations.v1.conversation.participant.ParticipantInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, 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 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.conversations.v1.conversation.participant.ParticipantInstance] + :returns: The fetched ParticipantInstance """ - 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) -> "ParticipantInstance": """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ParticipantInstance - :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.conversations.v1.conversation.participant.ParticipantPage + :returns: The fetched ParticipantInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return ParticipantPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated ParticipantInstance """ - Retrieve a specific page of ParticipantInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantPage + :returns: The updated ParticipantInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ParticipantPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ParticipantContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - """ - return ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=sid, - ) +class ParticipantContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, conversation_sid: str, sid: str): """ - Constructs a ParticipantContext + 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. - - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext """ - return ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=sid, + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution ) - def __repr__(self): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Provide a friendly representation + Deletes the ParticipantInstance - :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 ParticipantPage(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, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the ParticipantPage + Asynchronous coroutine that deletes the ParticipantInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param conversation_sid: The unique id of the Conversation for this participant. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantPage - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantPage + :returns: True if delete succeeds, False otherwise """ - super(ParticipantPage, self).__init__(version, response) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # 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) -> ParticipantInstance: """ - Build an instance of ParticipantInstance + Fetch the ParticipantInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> ParticipantInstance: """ - return '' + Asynchronous coroutine to fetch the ParticipantInstance -class ParticipantContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, conversation_sid, sid): + :returns: The fetched ParticipantInstance """ - Initialize the ParticipantContext - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this participant. - :param sid: A 34 character string that uniquely identifies this resource. + headers = values.of({}) - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext - """ - super(ParticipantContext, self).__init__(version) + headers["Accept"] = "application/json" - # Path Solution - self._solution = {'conversation_sid': conversation_sid, 'sid': sid, } - self._uri = '/Conversations/{conversation_sid}/Participants/{sid}'.format(**self._solution) + 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, date_created=values.unset, date_updated=values.unset, - attributes=values.unset, role_sid=values.unset, - messaging_binding_proxy_address=values.unset, - messaging_binding_projected_address=values.unset, - x_twilio_webhook_enabled=values.unset): + 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 datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param unicode role_sid: The SID of the Role to assign to the participant - :param unicode messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. - :param unicode messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 - :rtype: twilio.rest.conversations.v1.conversation.participant.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, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + 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 """ - Deletes the ParticipantInstance - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + 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 - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): - """ - Fetch the ParticipantInstance + headers["Accept"] = "application/json" - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + conversation_sid=self._solution["conversation_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 ParticipantInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ParticipantPage(Page): - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance - def __init__(self, version, payload, conversation_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the ParticipantInstance + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) - :returns: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + def __repr__(self) -> str: """ - super(ParticipantInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'conversation_sid': payload.get('conversation_sid'), - 'sid': payload.get('sid'), - 'identity': payload.get('identity'), - 'attributes': payload.get('attributes'), - 'messaging_binding': payload.get('messaging_binding'), - 'role_sid': payload.get('role_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'conversation_sid': conversation_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 ParticipantList(ListResource): - :returns: ParticipantContext for this ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantContext + def __init__(self, version: Version, conversation_sid: str): """ - if self._context is None: - self._context = ParticipantContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the ParticipantList - @property - def account_sid(self): - """ - :returns: The unique id of the Account responsible for this participant. - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def conversation_sid(self): """ - :returns: The unique id of the Conversation for this participant. - :rtype: unicode + 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: """ - return self._properties['conversation_sid'] + Create the ParticipantInstance - @property - def sid(self): + :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 """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + + 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 """ - return self._properties['sid'] - @property - def identity(self): + 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]: """ - :returns: A unique string identifier for the conversation participant as Chat User. - :rtype: unicode + 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 """ - return self._properties['identity'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def attributes(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: """ - :returns: An optional string metadata field you can use to store any data you wish. - :rtype: unicode + 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 """ - return self._properties['attributes'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def messaging_binding(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - :returns: Information about how this participant exchanges messages with the conversation. - :rtype: dict + 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 self._properties['messaging_binding'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def role_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - :returns: The SID of the Role to assign to the participant - :rtype: unicode + 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 self._properties['role_sid'] + 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, + ) -> ParticipantPage: """ - :returns: The date that this resource was created. - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The date that this resource was last updated. - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: An absolute URL for this participant. - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - def update(self, date_created=values.unset, date_updated=values.unset, - attributes=values.unset, role_sid=values.unset, - messaging_binding_proxy_address=values.unset, - messaging_binding_projected_address=values.unset, - x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> ParticipantPage: """ - Update the ParticipantInstance + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately - :param datetime date_created: The date that this resource was created. - :param datetime date_updated: The date that this resource was last updated. - :param unicode attributes: An optional string metadata field you can use to store any data you wish. - :param unicode role_sid: The SID of the Role to assign to the participant - :param unicode messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. - :param unicode messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The updated ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + :returns: Page of ParticipantInstance """ - return self._proxy.update( - 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - def delete(self, x_twilio_webhook_enabled=values.unset): + def get(self, sid: str) -> ParticipantContext: """ - Deletes the ParticipantInstance - - :param ParticipantInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Constructs a ParticipantContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> ParticipantContext: """ - Fetch the ParticipantInstance + Constructs a ParticipantContext - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.conversations.v1.conversation.participant.ParticipantInstance + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.fetch() + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_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/conversations/v1/conversation/webhook.py b/twilio/rest/conversations/v1/conversation/webhook.py index a025383e7d..837f88c26f 100644 --- a/twilio/rest/conversations/v1/conversation/webhook.py +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -1,483 +1,758 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 WebhookList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class WebhookInstance(InstanceResource): - def __init__(self, version, conversation_sid): - """ - Initialize the WebhookList + class Method(object): + GET = "GET" + POST = "POST" - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this webhook. + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookList - """ - super(WebhookList, self).__init__(version) + """ + :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") + ) - # Path Solution - self._solution = {'conversation_sid': conversation_sid, } - self._uri = '/Conversations/{conversation_sid}/Webhooks'.format(**self._solution) + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "WebhookContext": """ - 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 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.conversations.v1.conversation.webhook.WebhookInstance] + :returns: WebhookContext for this WebhookInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + if self._context is None: + self._context = WebhookContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(self) -> bool: """ - Lists WebhookInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the WebhookInstance - :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.conversations.v1.conversation.webhook.WebhookInstance] + :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 WebhookInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the WebhookInstance - :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 WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookPage + :returns: True if delete succeeds, False otherwise """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.delete_async() - return WebhookPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "WebhookInstance": """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately + Fetch the WebhookInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookPage + :returns: The fetched WebhookInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return WebhookPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, target, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_replay_after=values.unset): + async def fetch_async(self) -> "WebhookInstance": """ - Create the WebhookInstance + Asynchronous coroutine to fetch the WebhookInstance - :param WebhookInstance.Target target: The target of this webhook. - :param unicode configuration_url: The absolute url the webhook request should be sent to. - :param WebhookInstance.Method configuration_method: The HTTP method to be used when sending a webhook request. - :param unicode configuration_filters: The list of events, firing webhook event for this Conversation. - :param unicode configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param unicode configuration_flow_sid: The studio flow sid, where the webhook should be sent to. - :param unicode configuration_replay_after: The message index for which and it's successors the webhook will be replayed. - :returns: The created WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + :returns: The fetched 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return WebhookInstance(self._version, payload, conversation_sid=self._solution['conversation_sid'], ) + return await self._proxy.fetch_async() - def get(self, 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": """ - Constructs a WebhookContext + Update the WebhookInstance - :param sid: A 34 character string that uniquely identifies this resource. + :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: twilio.rest.conversations.v1.conversation.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookContext + :returns: The updated WebhookInstance """ - return WebhookContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + 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, + ) - def __call__(self, 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": """ - Constructs a WebhookContext + Asynchronous coroutine to update the WebhookInstance - :param sid: A 34 character string that uniquely identifies this resource. + :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: twilio.rest.conversations.v1.conversation.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookContext + :returns: The updated WebhookInstance """ - return WebhookContext(self._version, conversation_sid=self._solution['conversation_sid'], sid=sid, ) + 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): + 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 WebhookPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class WebhookContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, conversation_sid: str, sid: str): """ - Initialize the WebhookPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param conversation_sid: The unique id of the Conversation for this webhook. + Initialize the WebhookContext - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookPage - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookPage + :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(WebhookPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Webhooks/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of WebhookInstance + Deletes the WebhookInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + :returns: True if delete succeeds, False otherwise """ - return WebhookInstance(self._version, payload, conversation_sid=self._solution['conversation_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 WebhookInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class WebhookContext(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, conversation_sid, sid): + def fetch(self) -> WebhookInstance: """ - Initialize the WebhookContext + Fetch the WebhookInstance - :param Version version: Version that contains the resource - :param conversation_sid: The unique id of the Conversation for this webhook. - :param sid: A 34 character string that uniquely identifies this resource. - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookContext + :returns: The fetched WebhookInstance """ - super(WebhookContext, self).__init__(version) - # Path Solution - self._solution = {'conversation_sid': conversation_sid, 'sid': sid, } - self._uri = '/Conversations/{conversation_sid}/Webhooks/{sid}'.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 WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: """ - Fetch the WebhookInstance + Asynchronous coroutine to fetch the WebhookInstance + :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset): + 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 unicode configuration_url: The absolute url the webhook request should be sent to. - :param WebhookInstance.Method configuration_method: The HTTP method to be used when sending a webhook request. - :param unicode configuration_filters: The list of events, firing webhook event for this Conversation. - :param unicode configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param unicode configuration_flow_sid: The studio flow sid, where the webhook should be sent to. + :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 - :rtype: twilio.rest.conversations.v1.conversation.webhook.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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the WebhookInstance + Asynchronous coroutine to update the WebhookInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + 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 - :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 WebhookInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class WebhookPage(Page): - class Target(object): - WEBHOOK = "webhook" - TRIGGER = "trigger" - STUDIO = "studio" + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance - class Method(object): - GET = "GET" - POST = "POST" + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) - def __init__(self, version, payload, conversation_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the WebhookInstance + Provide a friendly representation - :returns: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + :returns: Machine friendly representation """ - super(WebhookInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'conversation_sid': payload.get('conversation_sid'), - 'target': payload.get('target'), - 'url': payload.get('url'), - 'configuration': payload.get('configuration'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } - # Context - self._context = None - self._solution = {'conversation_sid': conversation_sid, 'sid': sid or self._properties['sid'], } +class WebhookList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, conversation_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 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. - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookContext """ - if self._context is None: - self._context = WebhookContext( - self._version, - conversation_sid=self._solution['conversation_sid'], - sid=self._solution['sid'], - ) - return self._context + super().__init__(version) - @property - def sid(self): + # 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: """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def account_sid(self): + 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 """ - :returns: The unique id of the Account responsible for this conversation. - :rtype: unicode + + 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]: """ - return self._properties['account_sid'] + 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. - @property - def conversation_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 unique id of the Conversation for this webhook. - :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[WebhookInstance]: """ - return self._properties['conversation_sid'] + 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. - @property - def target(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 target of this webhook. - :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[WebhookInstance]: """ - return self._properties['target'] + Lists WebhookInstance 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: An absolute URL for this webhook. - :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[WebhookInstance]: """ - return self._properties['url'] + 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. - @property - def configuration(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 configuration of this webhook. - :rtype: dict + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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: """ - return self._properties['configuration'] + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - @property - def date_created(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 WebhookInstance """ - :returns: The date that this resource was 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 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: """ - return self._properties['date_created'] + Asynchronously retrieve a single page of WebhookInstance 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 WebhookInstance """ - :returns: The date that this resource was last 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 WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: """ - return self._properties['date_updated'] + 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 - def fetch(self): + :returns: Page of WebhookInstance """ - Fetch the WebhookInstance + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + async def get_page_async(self, target_url: str) -> WebhookPage: """ - return self._proxy.fetch() + 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 - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset): + :returns: Page of WebhookInstance """ - Update the WebhookInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :param unicode configuration_url: The absolute url the webhook request should be sent to. - :param WebhookInstance.Method configuration_method: The HTTP method to be used when sending a webhook request. - :param unicode configuration_filters: The list of events, firing webhook event for this Conversation. - :param unicode configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param unicode configuration_flow_sid: The studio flow sid, where the webhook should be sent to. + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext - :returns: The updated WebhookInstance - :rtype: twilio.rest.conversations.v1.conversation.webhook.WebhookInstance + :param sid: A 34 character string that uniquely identifies this resource. """ - 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, + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid ) - def delete(self): + def __call__(self, sid: str) -> WebhookContext: """ - Deletes the WebhookInstance + Constructs a WebhookContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies this resource. """ - return self._proxy.delete() + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_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/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/conversations/v1/webhook.py b/twilio/rest/conversations/v1/webhook.py deleted file mode 100644 index 48f4588b8d..0000000000 --- a/twilio/rest/conversations/v1/webhook.py +++ /dev/null @@ -1,316 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 WebhookList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the WebhookList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.conversations.v1.webhook.WebhookList - :rtype: twilio.rest.conversations.v1.webhook.WebhookList - """ - super(WebhookList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self): - """ - Constructs a WebhookContext - - :returns: twilio.rest.conversations.v1.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.webhook.WebhookContext - """ - return WebhookContext(self._version, ) - - def __call__(self): - """ - Constructs a WebhookContext - - :returns: twilio.rest.conversations.v1.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.webhook.WebhookContext - """ - return WebhookContext(self._version, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WebhookPage(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 WebhookPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.conversations.v1.webhook.WebhookPage - :rtype: twilio.rest.conversations.v1.webhook.WebhookPage - """ - super(WebhookPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of WebhookInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.conversations.v1.webhook.WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - return WebhookInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class WebhookContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the WebhookContext - - :param Version version: Version that contains the resource - - :returns: twilio.rest.conversations.v1.webhook.WebhookContext - :rtype: twilio.rest.conversations.v1.webhook.WebhookContext - """ - super(WebhookContext, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Conversations/Webhooks'.format(**self._solution) - - def fetch(self): - """ - Fetch the WebhookInstance - - :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return WebhookInstance(self._version, payload, ) - - def update(self, method=values.unset, filters=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - target=values.unset): - """ - Update the WebhookInstance - - :param unicode method: The HTTP method to be used when sending a webhook request. - :param unicode filters: The list of webhook event triggers that are enabled for this Service. - :param unicode pre_webhook_url: The absolute url the pre-event webhook request should be sent to. - :param unicode post_webhook_url: The absolute url the post-event webhook request should be sent to. - :param WebhookInstance.Target target: The routing target of the webhook. - - :returns: The updated WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - data = values.of({ - 'Method': method, - 'Filters': serialize.map(filters, lambda e: e), - 'PreWebhookUrl': pre_webhook_url, - 'PostWebhookUrl': post_webhook_url, - 'Target': target, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return WebhookInstance(self._version, payload, ) - - 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 WebhookInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - class Target(object): - WEBHOOK = "webhook" - FLEX = "flex" - - class Method(object): - GET = "GET" - POST = "POST" - - def __init__(self, version, payload): - """ - Initialize the WebhookInstance - - :returns: twilio.rest.conversations.v1.webhook.WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - super(WebhookInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'method': payload.get('method'), - 'filters': payload.get('filters'), - 'pre_webhook_url': payload.get('pre_webhook_url'), - 'post_webhook_url': payload.get('post_webhook_url'), - 'target': payload.get('target'), - 'url': payload.get('url'), - } - - # Context - self._context = None - 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 - - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookContext - """ - if self._context is None: - self._context = WebhookContext(self._version, ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique id of the Account responsible for this conversation. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def method(self): - """ - :returns: The HTTP method to be used when sending a webhook request. - :rtype: WebhookInstance.Method - """ - return self._properties['method'] - - @property - def filters(self): - """ - :returns: The list of webhook event triggers that are enabled for this Service. - :rtype: unicode - """ - return self._properties['filters'] - - @property - def pre_webhook_url(self): - """ - :returns: The absolute url the pre-event webhook request should be sent to. - :rtype: unicode - """ - return self._properties['pre_webhook_url'] - - @property - def post_webhook_url(self): - """ - :returns: The absolute url the post-event webhook request should be sent to. - :rtype: unicode - """ - return self._properties['post_webhook_url'] - - @property - def target(self): - """ - :returns: The routing target of the webhook. - :rtype: WebhookInstance.Target - """ - return self._properties['target'] - - @property - def url(self): - """ - :returns: An absolute URL for this webhook. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the WebhookInstance - - :returns: The fetched WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - return self._proxy.fetch() - - def update(self, method=values.unset, filters=values.unset, - pre_webhook_url=values.unset, post_webhook_url=values.unset, - target=values.unset): - """ - Update the WebhookInstance - - :param unicode method: The HTTP method to be used when sending a webhook request. - :param unicode filters: The list of webhook event triggers that are enabled for this Service. - :param unicode pre_webhook_url: The absolute url the pre-event webhook request should be sent to. - :param unicode post_webhook_url: The absolute url the post-event webhook request should be sent to. - :param WebhookInstance.Target target: The routing target of the webhook. - - :returns: The updated WebhookInstance - :rtype: twilio.rest.conversations.v1.webhook.WebhookInstance - """ - return self._proxy.update( - method=method, - filters=filters, - pre_webhook_url=pre_webhook_url, - post_webhook_url=post_webhook_url, - target=target, - ) - - 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/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 2b77934402..0000000000 --- a/twilio/rest/fax/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -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 3858b42ebc..0000000000 --- a/twilio/rest/fax/v1/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -r""" -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 f23a5e82ae..0000000000 --- a/twilio/rest/fax/v1/fax/__init__.py +++ /dev/null @@ -1,610 +0,0 @@ -# coding=utf-8 -r""" -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_: Retrieve only those faxes sent from this phone number - :param unicode to: Retrieve only those faxes sent to this phone number - :param datetime date_created_on_or_before: Retrieve only faxes created on or before this date - :param datetime date_created_after: Retrieve only faxes created after this 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.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']) - - 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_: Retrieve only those faxes sent from this phone number - :param unicode to: Retrieve only those faxes sent to this phone number - :param datetime date_created_on_or_before: Retrieve only faxes created on or before this date - :param datetime date_created_after: Retrieve only faxes created after this 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.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_: Retrieve only those faxes sent from this phone number - :param unicode to: Retrieve only those faxes sent to this phone number - :param datetime date_created_on_or_before: Retrieve only faxes created on or before this date - :param datetime date_created_after: Retrieve only faxes created after this 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 FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxPage - """ - data = 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(method='GET', uri=self._uri, params=data, ) - - 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 the FaxInstance - - :param unicode to: The phone number to receive the fax - :param unicode media_url: The URL of the PDF that contains the fax - :param FaxInstance.Quality quality: The quality of this fax - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode from_: The number the fax was sent from - :param unicode sip_auth_username: The username for SIP authentication - :param unicode sip_auth_password: The password for SIP authentication - :param bool store_media: Whether to store a copy of the sent media - :param unicode ttl: How long in minutes to try to send the fax - - :returns: The 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(method='POST', uri=self._uri, data=data, ) - - return FaxInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a FaxContext - - :param sid: The unique string that identifies the resource - - :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: The unique string that identifies the resource - - :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: The unique string that identifies the resource - - :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 the FaxInstance - - :returns: The fetched FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return FaxInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, status=values.unset): - """ - Update the FaxInstance - - :param FaxInstance.UpdateStatus status: The new status of the resource - - :returns: The updated FaxInstance - :rtype: twilio.rest.fax.v1.fax.FaxInstance - """ - data = values.of({'Status': status, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'from_': payload.get('from'), - 'to': payload.get('to'), - 'quality': payload.get('quality'), - 'media_sid': payload.get('media_sid'), - 'media_url': payload.get('media_url'), - 'num_pages': deserialize.integer(payload.get('num_pages')), - 'duration': deserialize.integer(payload.get('duration')), - 'status': payload.get('status'), - 'direction': payload.get('direction'), - 'api_version': payload.get('api_version'), - 'price': deserialize.decimal(payload.get('price')), - 'price_unit': payload.get('price_unit'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'links': payload.get('links'), - 'url': payload.get('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: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def from_(self): - """ - :returns: The number the fax was sent from - :rtype: unicode - """ - return self._properties['from_'] - - @property - def to(self): - """ - :returns: The phone number that received the fax - :rtype: unicode - """ - return self._properties['to'] - - @property - def quality(self): - """ - :returns: The quality of the fax - :rtype: FaxInstance.Quality - """ - return self._properties['quality'] - - @property - def media_sid(self): - """ - :returns: The SID of the FaxMedia resource that is associated with the Fax - :rtype: unicode - """ - return self._properties['media_sid'] - - @property - def media_url(self): - """ - :returns: The Twilio-hosted URL that can be used to download fax media - :rtype: unicode - """ - return self._properties['media_url'] - - @property - def num_pages(self): - """ - :returns: The number of pages contained in the fax document - :rtype: unicode - """ - return self._properties['num_pages'] - - @property - def duration(self): - """ - :returns: The time it took to transmit the fax - :rtype: unicode - """ - return self._properties['duration'] - - @property - def status(self): - """ - :returns: The status of the fax - :rtype: FaxInstance.Status - """ - return self._properties['status'] - - @property - def direction(self): - """ - :returns: The direction of the fax - :rtype: FaxInstance.Direction - """ - return self._properties['direction'] - - @property - def api_version(self): - """ - :returns: The API version used to transmit the fax - :rtype: unicode - """ - return self._properties['api_version'] - - @property - def price(self): - """ - :returns: The fax transmission price - :rtype: unicode - """ - return self._properties['price'] - - @property - def price_unit(self): - """ - :returns: The ISO 4217 currency used for billing - :rtype: unicode - """ - return self._properties['price_unit'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 formatted date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 formatted date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def links(self): - """ - :returns: The URLs of the fax's related resources - :rtype: unicode - """ - return self._properties['links'] - - @property - def url(self): - """ - :returns: The absolute URL of the fax resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FaxInstance - - :returns: The 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 new status of the resource - - :returns: The 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 4ed3b512a7..0000000000 --- a/twilio/rest/fax/v1/fax/fax_media.py +++ /dev/null @@ -1,371 +0,0 @@ -# coding=utf-8 -r""" -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: The SID of the fax the FaxMedia resource is associated with - - :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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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: The unique string that identifies the resource to fetch - - :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: The unique string that identifies the resource to fetch - - :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: The SID of the fax the FaxMedia resource is associated with - - :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: The SID of the fax with the FaxMedia resource to fetch - :param sid: The unique string that identifies the resource to fetch - - :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 the FaxMediaInstance - - :returns: The fetched FaxMediaInstance - :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'fax_sid': payload.get('fax_sid'), - 'content_type': payload.get('content_type'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def fax_sid(self): - """ - :returns: The SID of the fax the FaxMedia resource is associated with - :rtype: unicode - """ - return self._properties['fax_sid'] - - @property - def content_type(self): - """ - :returns: The content type of the stored fax media - :rtype: unicode - """ - return self._properties['content_type'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The absolute URL of the FaxMedia resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FaxMediaInstance - - :returns: The 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 index f25eb4e038..8f679516c1 100644 --- a/twilio/rest/flex_api/__init__.py +++ b/twilio/rest/flex_api/__init__.py @@ -1,74 +1,185 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.flex_api.v1 import V1 +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(Domain): +class FlexApi(FlexApiBase): + @property + def assessments(self) -> AssessmentsList: + warn( + "assessments is deprecated. Use v1.assessments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.assessments - def __init__(self, twilio): - """ - Initialize the FlexApi Domain + @property + def channel(self) -> ChannelList: + warn( + "channel is deprecated. Use v1.channel instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.channel - :returns: Domain for FlexApi - :rtype: twilio.rest.flex_api.FlexApi - """ - super(FlexApi, self).__init__(twilio) + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration - self.base_url = 'https://flex-api.twilio.com' + @property + def flex_flow(self) -> FlexFlowList: + warn( + "flex_flow is deprecated. Use v1.flex_flow instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.flex_flow - # Versions - self._v1 = None + @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 v1(self): - """ - :returns: Version v1 of flex_api - :rtype: twilio.rest.flex_api.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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 channel(self): - """ - :rtype: twilio.rest.flex_api.v1.channel.ChannelList - """ - return self.v1.channel + 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 configuration(self): - """ - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList - """ - return self.v1.configuration + 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 flex_flow(self): - """ - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - """ - return self.v1.flex_flow + 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 web_channel(self): - """ - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelList - """ - return self.v1.web_channel + def insights_segments(self) -> InsightsSegmentsList: + warn( + "insights_segments is deprecated. Use v1.insights_segments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_segments - def __repr__(self): - """ - Provide a friendly representation + @property + def insights_session(self) -> InsightsSessionList: + warn( + "insights_session is deprecated. Use v1.insights_session instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_session - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index 1bee2c560c..eeb00227e9 100644 --- a/twilio/rest/flex_api/v1/__init__.py +++ b/twilio/rest/flex_api/v1/__init__.py @@ -1,75 +1,245 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V1 version of FlexApi - :returns: V1 version of FlexApi - :rtype: twilio.rest.flex_api.v1.V1.V1 + :param domain: The Twilio.flex_api domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._channel = None - self._configuration = None - self._flex_flow = None - self._web_channel = None + 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 channel(self): - """ - :rtype: twilio.rest.flex_api.v1.channel.ChannelList - """ + 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): - """ - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList - """ + def configuration(self) -> ConfigurationList: if self._configuration is None: self._configuration = ConfigurationList(self) return self._configuration @property - def flex_flow(self): - """ - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - """ + def flex_flow(self) -> FlexFlowList: if self._flex_flow is None: self._flex_flow = FlexFlowList(self) return self._flex_flow @property - def web_channel(self): - """ - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + 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 index cf8548867c..aa98ff8d31 100644 --- a/twilio/rest/flex_api/v1/channel.py +++ b/twilio/rest/flex_api/v1/channel.py @@ -1,403 +1,575 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 ChannelList(ListResource): - """ """ +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") + ) - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": """ - Initialize the ChannelList + 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: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.flex_api.v1.channel.ChannelList - :rtype: twilio.rest.flex_api.v1.channel.ChannelList + def delete(self) -> bool: """ - super(ChannelList, self).__init__(version) + Deletes the ChannelInstance - # Path Solution - self._solution = {} - self._uri = '/Channels'.format(**self._solution) - def stream(self, 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. - - :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.flex_api.v1.channel.ChannelInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ChannelInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch the ChannelInstance - :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.flex_api.v1.channel.ChannelInstance] + :returns: The fetched ChannelInstance """ - 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) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ChannelInstance - :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.flex_api.v1.channel.ChannelPage + :returns: The fetched ChannelInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ChannelPage(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 ChannelInstance 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 ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelPage +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + 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) - return ChannelPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/{sid}".format(**self._solution) - def create(self, flex_flow_sid, identity, chat_user_friendly_name, - chat_friendly_name, target=values.unset, - chat_unique_name=values.unset, pre_engagement_data=values.unset, - task_sid=values.unset, task_attributes=values.unset, - long_lived=values.unset): + def delete(self) -> bool: """ - Create the ChannelInstance + Deletes the ChannelInstance - :param unicode flex_flow_sid: The SID of the FlexFlow - :param unicode identity: The identity value that identifies the new resource's chat User - :param unicode chat_user_friendly_name: The chat participant's friendly name - :param unicode chat_friendly_name: The chat channel's friendly name - :param unicode target: The Target Contact Identity - :param unicode chat_unique_name: The chat channel's unique name - :param unicode pre_engagement_data: The pre-engagement data - :param unicode task_sid: The SID of the TaskRouter task - :param unicode task_attributes: The task attributes to be added for the TaskRouter Task - :param bool long_lived: Whether to create the channel as long-lived - :returns: The created ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + :returns: True if delete succeeds, False otherwise """ - 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': long_lived, - }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return ChannelInstance(self._version, payload, ) + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a ChannelContext + Asynchronous coroutine that deletes the ChannelInstance - :param sid: The SID that identifies the Flex chat channel resource to fetch - :returns: twilio.rest.flex_api.v1.channel.ChannelContext - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext + :returns: True if delete succeeds, False otherwise """ - return ChannelContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a ChannelContext + headers = values.of({}) - :param sid: The SID that identifies the Flex chat channel resource to fetch + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: twilio.rest.flex_api.v1.channel.ChannelContext - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext + def fetch(self) -> ChannelInstance: """ - return ChannelContext(self._version, sid=sid, ) + Fetch the ChannelInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched ChannelInstance """ - return '' + headers = values.of({}) -class ChannelPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the ChannelPage + 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 + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.flex_api.v1.channel.ChannelPage - :rtype: twilio.rest.flex_api.v1.channel.ChannelPage + async def fetch_async(self) -> ChannelInstance: """ - super(ChannelPage, self).__init__(version, response) + Asynchronous coroutine to fetch the ChannelInstance - # Path Solution - self._solution = solution - def get_instance(self, payload): + :returns: The fetched ChannelInstance """ - Build an instance of ChannelInstance - :param dict payload: Payload response from the API + headers = values.of({}) - :returns: twilio.rest.flex_api.v1.channel.ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance - """ - return ChannelInstance(self._version, payload, ) + 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): + 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 ChannelContext(InstanceContext): - """ """ +class ChannelPage(Page): - def __init__(self, version, sid): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ - Initialize the ChannelContext - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the Flex chat channel resource to fetch + Build an instance of ChannelInstance - :returns: twilio.rest.flex_api.v1.channel.ChannelContext - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext + :param payload: Payload response from the API """ - super(ChannelContext, self).__init__(version) + return ChannelInstance(self._version, payload) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Channels/{sid}'.format(**self._solution) - - def fetch(self): + def __repr__(self) -> str: """ - Fetch the ChannelInstance + Provide a friendly representation - :returns: The fetched ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + :returns: Machine friendly representation """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + return "" - return ChannelInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): +class ChannelList(ListResource): + + def __init__(self, version: Version): """ - Deletes the ChannelInstance + Initialize the ChannelList + + :param version: Version that contains the resource - :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + super().__init__(version) + + self._uri = "/Channels" - def __repr__(self): + 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: """ - Provide a friendly representation + Create the ChannelInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -class ChannelInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, sid=None): - """ - Initialize the ChannelInstance + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.flex_api.v1.channel.ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + 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 """ - super(ChannelInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'flex_flow_sid': payload.get('flex_flow_sid'), - 'sid': payload.get('sid'), - 'user_sid': payload.get('user_sid'), - 'task_sid': payload.get('task_sid'), - 'url': payload.get('url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } + 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"}) - # 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: ChannelContext for this ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelContext - """ - if self._context is None: - self._context = ChannelContext(self._version, sid=self._solution['sid'], ) - return self._context + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource and owns this Workflow - :rtype: unicode + return ChannelInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: """ - return self._properties['account_sid'] + 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. - @property - def flex_flow_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 of the FlexFlow - :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[ChannelInstance]: """ - return self._properties['flex_flow_sid'] + 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. - @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 unique string that identifies the 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[ChannelInstance]: """ - return self._properties['sid'] + Lists ChannelInstance 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): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 SID of the chat user - :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[ChannelInstance]: """ - return self._properties['user_sid'] + 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. - @property - def task_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, + ) -> ChannelPage: """ - :returns: The SID of the TaskRouter task - :rtype: unicode + 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 """ - return self._properties['task_sid'] + 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 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: """ - :returns: The absolute URL of the Flex chat channel resource - :rtype: unicode + 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 """ - return self._properties['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 ChannelPage(self._version, response) + + def get_page(self, target_url: str) -> ChannelPage: """ - :returns: The ISO 8601 date and time in GMT when the Flex chat channel was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - :returns: The ISO 8601 date and time in GMT when the Flex chat channel was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response) - def fetch(self): + def get(self, sid: str) -> ChannelContext: """ - Fetch the ChannelInstance + Constructs a ChannelContext - :returns: The fetched ChannelInstance - :rtype: twilio.rest.flex_api.v1.channel.ChannelInstance + :param sid: The SID of the Flex chat channel resource to fetch. """ - return self._proxy.fetch() + return ChannelContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> ChannelContext: """ - Deletes the ChannelInstance + Constructs a ChannelContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Flex chat channel resource to fetch. """ - return self._proxy.delete() + return ChannelContext(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/flex_api/v1/configuration.py b/twilio/rest/flex_api/v1/configuration.py index b6fd87b3b1..28a66be036 100644 --- a/twilio/rest/flex_api/v1/configuration.py +++ b/twilio/rest/flex_api/v1/configuration.py @@ -1,575 +1,439 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource -from twilio.base.page import Page - - -class ConfigurationList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the ConfigurationList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationList - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList - """ - super(ConfigurationList, self).__init__(version) +class ConfigurationInstance(InstanceResource): - # Path Solution - self._solution = {} + class Status(object): + OK = "ok" + INPROGRESS = "inprogress" + NOTSTARTED = "notstarted" - def get(self): + """ + :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": """ - Constructs a 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: twilio.rest.flex_api.v1.configuration.ConfigurationContext - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext + :returns: ConfigurationContext for this ConfigurationInstance """ - return ConfigurationContext(self._version, ) + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context - def __call__(self): + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": """ - Constructs a ConfigurationContext + Fetch the ConfigurationInstance - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationContext - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext - """ - return ConfigurationContext(self._version, ) + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - def __repr__(self): + :returns: The fetched ConfigurationInstance """ - Provide a friendly representation + return self._proxy.fetch( + ui_version=ui_version, + ) - :returns: Machine friendly representation - :rtype: str + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": """ - return '' + Asynchronous coroutine to fetch the ConfigurationInstance + :param ui_version: The Pinned UI version of the Configuration resource to fetch. -class ConfigurationPage(Page): - """ """ + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async( + ui_version=ui_version, + ) - def __init__(self, version, response, solution): + def update( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": """ - Initialize the ConfigurationPage + Update the ConfigurationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param body: - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationPage - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationPage + :returns: The updated ConfigurationInstance """ - super(ConfigurationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.update( + body=body, + ) - def get_instance(self, payload): + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": """ - Build an instance of ConfigurationInstance + Asynchronous coroutine to update the ConfigurationInstance - :param dict payload: Payload response from the API + :param body: - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance + :returns: The updated ConfigurationInstance """ - return ConfigurationInstance(self._version, payload, ) + return await self._proxy.update_async( + body=body, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class ConfigurationContext(InstanceContext): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the ConfigurationContext - :param Version version: Version that contains the resource - - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationContext - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext + :param version: Version that contains the resource """ - super(ConfigurationContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/Configuration'.format(**self._solution) + self._uri = "/Configuration" - def fetch(self, ui_version=values.unset): + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: """ Fetch the ConfigurationInstance - :param unicode ui_version: The Pinned UI version of the Configuration resource to fetch + :param ui_version: The Pinned UI version of the Configuration resource to fetch. :returns: The fetched ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - """ - data = values.of({'UiVersion': ui_version, }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - - return ConfigurationInstance(self._version, payload, ) - - def create(self): - """ - Create the ConfigurationInstance - - :returns: The created ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - """ - payload = self._version.create(method='POST', uri=self._uri, ) - - return ConfigurationInstance(self._version, payload, ) - - def update(self): - """ - Update the ConfigurationInstance - - :returns: The updated ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - """ - payload = self._version.update(method='POST', uri=self._uri, ) - - return ConfigurationInstance(self._version, payload, ) - - 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 ConfigurationInstance(InstanceResource): - """ """ - - class Status(object): - OK = "ok" - INPROGRESS = "inprogress" - NOTSTARTED = "notstarted" - - def __init__(self, version, payload): - """ - Initialize the ConfigurationInstance - - :returns: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance - """ - super(ConfigurationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'attributes': payload.get('attributes'), - 'status': payload.get('status'), - 'taskrouter_workspace_sid': payload.get('taskrouter_workspace_sid'), - 'taskrouter_target_workflow_sid': payload.get('taskrouter_target_workflow_sid'), - 'taskrouter_target_taskqueue_sid': payload.get('taskrouter_target_taskqueue_sid'), - 'taskrouter_taskqueues': payload.get('taskrouter_taskqueues'), - 'taskrouter_skills': payload.get('taskrouter_skills'), - 'taskrouter_worker_channels': payload.get('taskrouter_worker_channels'), - 'taskrouter_worker_attributes': payload.get('taskrouter_worker_attributes'), - 'taskrouter_offline_activity_sid': payload.get('taskrouter_offline_activity_sid'), - 'runtime_domain': payload.get('runtime_domain'), - 'messaging_service_instance_sid': payload.get('messaging_service_instance_sid'), - 'chat_service_instance_sid': payload.get('chat_service_instance_sid'), - 'flex_service_instance_sid': payload.get('flex_service_instance_sid'), - 'ui_language': payload.get('ui_language'), - 'ui_attributes': payload.get('ui_attributes'), - 'ui_dependencies': payload.get('ui_dependencies'), - 'ui_version': payload.get('ui_version'), - 'service_version': payload.get('service_version'), - 'call_recording_enabled': payload.get('call_recording_enabled'), - 'call_recording_webhook_url': payload.get('call_recording_webhook_url'), - 'crm_enabled': payload.get('crm_enabled'), - 'crm_type': payload.get('crm_type'), - 'crm_callback_url': payload.get('crm_callback_url'), - 'crm_fallback_url': payload.get('crm_fallback_url'), - 'crm_attributes': payload.get('crm_attributes'), - 'public_attributes': payload.get('public_attributes'), - 'plugin_service_enabled': payload.get('plugin_service_enabled'), - 'plugin_service_attributes': payload.get('plugin_service_attributes'), - 'integrations': payload.get('integrations'), - 'outbound_call_flows': payload.get('outbound_call_flows'), - 'serverless_service_sids': payload.get('serverless_service_sids'), - 'queue_stats_configuration': payload.get('queue_stats_configuration'), - 'url': payload.get('url'), - } - - # Context - self._context = None - 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 - - :returns: ConfigurationContext for this ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationContext - """ - if self._context is None: - self._context = ConfigurationContext(self._version, ) - return self._context - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode """ - return self._properties['account_sid'] - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Configuration resource was created - :rtype: datetime - """ - return self._properties['date_created'] + data = values.of( + { + "UiVersion": ui_version, + } + ) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the Configuration resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers = values.of({}) - @property - def attributes(self): - """ - :returns: An object that contains application-specific data - :rtype: dict - """ - return self._properties['attributes'] + headers["Accept"] = "application/json" - @property - def status(self): - """ - :returns: The status of the Flex onboarding - :rtype: ConfigurationInstance.Status - """ - return self._properties['status'] + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def taskrouter_workspace_sid(self): - """ - :returns: The SID of the TaskRouter Workspace - :rtype: unicode - """ - return self._properties['taskrouter_workspace_sid'] + return ConfigurationInstance( + self._version, + payload, + ) - @property - def taskrouter_target_workflow_sid(self): - """ - :returns: The SID of the TaskRouter target Workflow - :rtype: unicode + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: """ - return self._properties['taskrouter_target_workflow_sid'] + Asynchronous coroutine to fetch the ConfigurationInstance - @property - def taskrouter_target_taskqueue_sid(self): - """ - :returns: The SID of the TaskRouter Target TaskQueue - :rtype: unicode - """ - return self._properties['taskrouter_target_taskqueue_sid'] + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - @property - def taskrouter_taskqueues(self): - """ - :returns: The list of TaskRouter TaskQueues - :rtype: dict + :returns: The fetched ConfigurationInstance """ - return self._properties['taskrouter_taskqueues'] - @property - def taskrouter_skills(self): - """ - :returns: The Skill description for TaskRouter workers - :rtype: dict - """ - return self._properties['taskrouter_skills'] + data = values.of( + { + "UiVersion": ui_version, + } + ) - @property - def taskrouter_worker_channels(self): - """ - :returns: The TaskRouter default channel capacities and availability for workers - :rtype: dict - """ - return self._properties['taskrouter_worker_channels'] + headers = values.of({}) - @property - def taskrouter_worker_attributes(self): - """ - :returns: The TaskRouter Worker attributes - :rtype: dict - """ - return self._properties['taskrouter_worker_attributes'] + headers["Accept"] = "application/json" - @property - def taskrouter_offline_activity_sid(self): - """ - :returns: The TaskRouter SID of the offline activity - :rtype: unicode - """ - return self._properties['taskrouter_offline_activity_sid'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def runtime_domain(self): - """ - :returns: The URL where the Flex instance is hosted - :rtype: unicode - """ - return self._properties['runtime_domain'] + return ConfigurationInstance( + self._version, + payload, + ) - @property - def messaging_service_instance_sid(self): + def update( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: """ - :returns: The SID of the Messaging service instance - :rtype: unicode - """ - return self._properties['messaging_service_instance_sid'] + Update the ConfigurationInstance - @property - def chat_service_instance_sid(self): - """ - :returns: The SID of the chat service this user belongs to - :rtype: unicode - """ - return self._properties['chat_service_instance_sid'] + :param body: - @property - def flex_service_instance_sid(self): - """ - :returns: The SID of the Flex service instance - :rtype: unicode + :returns: The updated ConfigurationInstance """ - return self._properties['flex_service_instance_sid'] + data = body.to_dict() - @property - def ui_language(self): - """ - :returns: The primary language of the Flex UI - :rtype: unicode - """ - return self._properties['ui_language'] + headers = values.of({}) - @property - def ui_attributes(self): - """ - :returns: The object that describes Flex UI characteristics and settings - :rtype: dict - """ - return self._properties['ui_attributes'] + headers["Content-Type"] = "application/json" - @property - def ui_dependencies(self): - """ - :returns: The object that defines the NPM packages and versions to be used in Hosted Flex - :rtype: dict - """ - return self._properties['ui_dependencies'] + headers["Accept"] = "application/json" - @property - def ui_version(self): - """ - :returns: The Pinned UI version - :rtype: unicode - """ - return self._properties['ui_version'] + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def service_version(self): - """ - :returns: The Flex Service version - :rtype: unicode - """ - return self._properties['service_version'] + return ConfigurationInstance(self._version, payload) - @property - def call_recording_enabled(self): + async def update_async( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: """ - :returns: Whether call recording is enabled - :rtype: bool - """ - return self._properties['call_recording_enabled'] + Asynchronous coroutine to update the ConfigurationInstance - @property - def call_recording_webhook_url(self): - """ - :returns: The call recording webhook URL - :rtype: unicode - """ - return self._properties['call_recording_webhook_url'] + :param body: - @property - def crm_enabled(self): - """ - :returns: Whether CRM is present for Flex - :rtype: bool - """ - return self._properties['crm_enabled'] - - @property - def crm_type(self): - """ - :returns: The CRM Type - :rtype: unicode + :returns: The updated ConfigurationInstance """ - return self._properties['crm_type'] + data = body.to_dict() - @property - def crm_callback_url(self): - """ - :returns: The CRM Callback URL - :rtype: unicode - """ - return self._properties['crm_callback_url'] + headers = values.of({}) - @property - def crm_fallback_url(self): - """ - :returns: The CRM Fallback URL - :rtype: unicode - """ - return self._properties['crm_fallback_url'] + headers["Content-Type"] = "application/json" - @property - def crm_attributes(self): - """ - :returns: An object that contains the CRM attributes - :rtype: dict - """ - return self._properties['crm_attributes'] + headers["Accept"] = "application/json" - @property - def public_attributes(self): - """ - :returns: The list of public attributes - :rtype: dict - """ - return self._properties['public_attributes'] + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def plugin_service_enabled(self): - """ - :returns: Whether the plugin service enabled - :rtype: bool - """ - return self._properties['plugin_service_enabled'] + return ConfigurationInstance(self._version, payload) - @property - def plugin_service_attributes(self): + def __repr__(self) -> str: """ - :returns: The plugin service attributes - :rtype: dict - """ - return self._properties['plugin_service_attributes'] - - @property - def integrations(self): - """ - :returns: A list of objects that contain the configurations for the Integrations supported in this configuration - :rtype: dict - """ - return self._properties['integrations'] + Provide a friendly representation - @property - def outbound_call_flows(self): - """ - :returns: The list of outbound call flows - :rtype: dict + :returns: Machine friendly representation """ - return self._properties['outbound_call_flows'] - @property - def serverless_service_sids(self): - """ - :returns: The list of serverless service SIDs - :rtype: unicode - """ - return self._properties['serverless_service_sids'] + return "" - @property - def queue_stats_configuration(self): - """ - :returns: Configurable parameters for Queues Statistics - :rtype: dict - """ - return self._properties['queue_stats_configuration'] - @property - def url(self): - """ - :returns: The absolute URL of the Configuration resource - :rtype: unicode - """ - return self._properties['url'] +class ConfigurationList(ListResource): - def fetch(self, ui_version=values.unset): + def __init__(self, version: Version): """ - Fetch the ConfigurationInstance + Initialize the ConfigurationList - :param unicode ui_version: The Pinned UI version of the Configuration resource to fetch + :param version: Version that contains the resource - :returns: The fetched ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ - return self._proxy.fetch(ui_version=ui_version, ) + super().__init__(version) - def create(self): + def get(self) -> ConfigurationContext: """ - Create the ConfigurationInstance + Constructs a ConfigurationContext - :returns: The created ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ - return self._proxy.create() + return ConfigurationContext(self._version) - def update(self): + def __call__(self) -> ConfigurationContext: """ - Update the ConfigurationInstance + Constructs a ConfigurationContext - :returns: The updated ConfigurationInstance - :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ - return self._proxy.update() + return ConfigurationContext(self._version) - 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/flex_api/v1/flex_flow.py b/twilio/rest/flex_api/v1/flex_flow.py index 262091add4..0ae2634666 100644 --- a/twilio/rest/flex_api/v1/flex_flow.py +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -1,611 +1,965 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 FlexFlowList(ListResource): - """ """ +class FlexFlowInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the FlexFlowList + class ChannelType(object): + WEB = "web" + SMS = "sms" + FACEBOOK = "facebook" + WHATSAPP = "whatsapp" + LINE = "line" + CUSTOM = "custom" - :param Version version: Version that contains the resource + class IntegrationType(object): + STUDIO = "studio" + EXTERNAL = "external" + TASK = "task" - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList - """ - super(FlexFlowList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/FlexFlows'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlexFlowContext] = None - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + @property + def _proxy(self) -> "FlexFlowContext": """ - 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. + 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` of the FlexFlow resources to read - :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: FlexFlowContext for this FlexFlowInstance + """ + if self._context is None: + self._context = FlexFlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the FlexFlowInstance - page = self.page(friendly_name=friendly_name, page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 FlexFlowInstance 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 FlexFlowInstance - :param unicode friendly_name: The `friendly_name` of the FlexFlow resources to read - :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.flex_api.v1.flex_flow.FlexFlowInstance] + :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) -> "FlexFlowInstance": """ - Retrieve a single page of FlexFlowInstance records from the API. - Request is executed immediately + Fetch the FlexFlowInstance - :param unicode friendly_name: The `friendly_name` of the FlexFlow resources to read - :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 FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage + :returns: The fetched FlexFlowInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "FlexFlowInstance": + """ + Asynchronous coroutine to fetch the FlexFlowInstance - return FlexFlowPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched FlexFlowInstance """ - Retrieve a specific page of FlexFlowInstance records from the API. - Request is executed immediately + 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 str target_url: API-generated URL for the requested results page + :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: Page of FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage + :returns: The updated FlexFlowInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return FlexFlowPage(self._version, response, self._solution) + 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. - def create(self, friendly_name, chat_service_sid, channel_type, - contact_identity=values.unset, enabled=values.unset, - integration_type=values.unset, integration_flow_sid=values.unset, - integration_url=values.unset, integration_workspace_sid=values.unset, - integration_workflow_sid=values.unset, - integration_channel=values.unset, integration_timeout=values.unset, - integration_priority=values.unset, - integration_creation_on_message=values.unset, - long_lived=values.unset, janitor_enabled=values.unset, - integration_retry_count=values.unset): + :returns: The updated FlexFlowInstance """ - Create the 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, + ) - :param unicode friendly_name: A string to describe the resource - :param unicode chat_service_sid: The SID of the chat service - :param FlexFlowInstance.ChannelType channel_type: The channel type - :param unicode contact_identity: The channel contact's Identity - :param bool enabled: Whether the new FlexFlow is enabled - :param FlexFlowInstance.IntegrationType integration_type: The integration type - :param unicode integration_flow_sid: The SID of the Flow - :param unicode integration_url: The External Webhook URL - :param unicode integration_workspace_sid: The Workspace SID for a new task - :param unicode integration_workflow_sid: The Workflow SID for a new task - :param unicode integration_channel: The task channel for a new task - :param unicode integration_timeout: The task timeout in seconds for a new task - :param unicode integration_priority: The task priority of a new task - :param bool integration_creation_on_message: Whether to create a task when the first message arrives - :param bool long_lived: Reuse this chat channel for future interactions with a contact - :param bool janitor_enabled: Remove active Proxy sessions if the corresponding Task is deleted - :param unicode integration_retry_count: The number of times to retry the webhook if the first attempt fails + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: The created FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ChatServiceSid': chat_service_sid, - 'ChannelType': channel_type, - 'ContactIdentity': contact_identity, - 'Enabled': 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': integration_creation_on_message, - 'LongLived': long_lived, - 'JanitorEnabled': janitor_enabled, - 'Integration.RetryCount': integration_retry_count, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return FlexFlowInstance(self._version, payload, ) - - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a FlexFlowContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext +class FlexFlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return FlexFlowContext(self._version, sid=sid, ) + Initialize the FlexFlowContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The SID of the Flex Flow resource to update. """ - Constructs a FlexFlowContext + super().__init__(version) - :param sid: The SID that identifies the resource to fetch + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/FlexFlows/{sid}".format(**self._solution) - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext + def delete(self) -> bool: """ - return FlexFlowContext(self._version, sid=sid, ) + Deletes the FlexFlowInstance - 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 FlexFlowPage(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 FlexFlowPage + Asynchronous coroutine that deletes the FlexFlowInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowPage + :returns: True if delete succeeds, False otherwise """ - super(FlexFlowPage, 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) -> FlexFlowInstance: """ - Build an instance of FlexFlowInstance + Fetch the FlexFlowInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance + :returns: The fetched FlexFlowInstance """ - return FlexFlowInstance(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 FlexFlowContext(InstanceContext): - """ """ + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> FlexFlowInstance: """ - Initialize the FlexFlowContext + Asynchronous coroutine to fetch the FlexFlowInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext + :returns: The fetched FlexFlowInstance """ - super(FlexFlowContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/FlexFlows/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the FlexFlowInstance + headers["Accept"] = "application/json" - :returns: The fetched FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - return FlexFlowInstance(self._version, payload, sid=self._solution['sid'], ) + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, chat_service_sid=values.unset, - channel_type=values.unset, contact_identity=values.unset, - enabled=values.unset, integration_type=values.unset, - integration_flow_sid=values.unset, integration_url=values.unset, - integration_workspace_sid=values.unset, - integration_workflow_sid=values.unset, - integration_channel=values.unset, integration_timeout=values.unset, - integration_priority=values.unset, - integration_creation_on_message=values.unset, - long_lived=values.unset, janitor_enabled=values.unset, - integration_retry_count=values.unset): + 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 unicode friendly_name: A string to describe the resource - :param unicode chat_service_sid: The SID of the chat service - :param FlexFlowInstance.ChannelType channel_type: The channel type - :param unicode contact_identity: The channel contact's Identity - :param bool enabled: Whether the FlexFlow is enabled - :param FlexFlowInstance.IntegrationType integration_type: The integration type - :param unicode integration_flow_sid: The SID of the Flow - :param unicode integration_url: The External Webhook URL - :param unicode integration_workspace_sid: The Workspace SID for a new task - :param unicode integration_workflow_sid: The Workflow SID for a new task - :param unicode integration_channel: task channel for a new task - :param unicode integration_timeout: The task timeout in seconds for a new task - :param unicode integration_priority: The task priority of a new task - :param bool integration_creation_on_message: Whether to create a task when the first message arrives - :param bool long_lived: Reuse this chat channel for future interactions with a contact - :param bool janitor_enabled: Remove active Proxy sessions if the corresponding Task is deleted. - :param unicode integration_retry_count: The number of times to retry the webhook if the first attempt fails + :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 - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ChatServiceSid': chat_service_sid, - 'ChannelType': channel_type, - 'ContactIdentity': contact_identity, - 'Enabled': 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': integration_creation_on_message, - 'LongLived': long_lived, - 'JanitorEnabled': janitor_enabled, - 'Integration.RetryCount': integration_retry_count, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return FlexFlowInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): """ - Deletes the FlexFlowInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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({}) - def __repr__(self): - """ - Provide a friendly representation + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers["Accept"] = "application/json" + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) -class FlexFlowInstance(InstanceResource): - """ """ + 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. - class ChannelType(object): - WEB = "web" - SMS = "sms" - FACEBOOK = "facebook" - WHATSAPP = "whatsapp" - LINE = "line" - CUSTOM = "custom" + :returns: The updated FlexFlowInstance + """ - class IntegrationType(object): - STUDIO = "studio" - EXTERNAL = "external" - TASK = "task" + 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({}) - def __init__(self, version, payload, sid=None): - """ - Initialize the FlexFlowInstance - - :returns: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance - """ - super(FlexFlowInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'chat_service_sid': payload.get('chat_service_sid'), - 'channel_type': payload.get('channel_type'), - 'contact_identity': payload.get('contact_identity'), - 'enabled': payload.get('enabled'), - 'integration_type': payload.get('integration_type'), - 'integration': payload.get('integration'), - 'long_lived': payload.get('long_lived'), - 'janitor_enabled': payload.get('janitor_enabled'), - 'url': payload.get('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.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: FlexFlowContext for this FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowContext - """ - if self._context is None: - self._context = FlexFlowContext(self._version, sid=self._solution['sid'], ) - return self._context + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['date_created'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] +class FlexFlowPage(Page): - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: """ - return self._properties['friendly_name'] + Build an instance of FlexFlowInstance - @property - def chat_service_sid(self): + :param payload: Payload response from the API """ - :returns: The SID of the chat service - :rtype: unicode + return FlexFlowInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['chat_service_sid'] + Provide a friendly representation - @property - def channel_type(self): + :returns: Machine friendly representation """ - :returns: The channel type - :rtype: FlexFlowInstance.ChannelType + return "" + + +class FlexFlowList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['channel_type'] + Initialize the FlexFlowList - @property - def contact_identity(self): + :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: """ - :returns: The channel contact's Identity - :rtype: unicode + 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 """ - return self._properties['contact_identity'] - @property - def enabled(self): + 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 """ - :returns: Whether the FlexFlow is enabled - :rtype: bool + + 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]: """ - return self._properties['enabled'] + 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. - @property - def integration_type(self): + :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 """ - :returns: The integration type - :rtype: FlexFlowInstance.IntegrationType + 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]: """ - return self._properties['integration_type'] + 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. - @property - def integration(self): + :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 """ - :returns: An object that contains specific parameters for the integration - :rtype: dict + 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]: """ - return self._properties['integration'] + Lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def long_lived(self): + :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]: """ - :returns: Re-use this chat channel for future interactions with a contact - :rtype: bool + 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: """ - return self._properties['long_lived'] + Retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately - @property - def janitor_enabled(self): + :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 """ - :returns: Remove active Proxy sessions if the corresponding Task is deleted. - :rtype: bool + 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: """ - return self._properties['janitor_enabled'] + Asynchronously retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the FlexFlow resource - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of FlexFlowInstance 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 FlexFlowInstance """ - Fetch the FlexFlowInstance + response = self._version.domain.twilio.request("GET", target_url) + return FlexFlowPage(self._version, response) - :returns: The fetched FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance + async def get_page_async(self, target_url: str) -> FlexFlowPage: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset, chat_service_sid=values.unset, - channel_type=values.unset, contact_identity=values.unset, - enabled=values.unset, integration_type=values.unset, - integration_flow_sid=values.unset, integration_url=values.unset, - integration_workspace_sid=values.unset, - integration_workflow_sid=values.unset, - integration_channel=values.unset, integration_timeout=values.unset, - integration_priority=values.unset, - integration_creation_on_message=values.unset, - long_lived=values.unset, janitor_enabled=values.unset, - integration_retry_count=values.unset): + :returns: Page of FlexFlowInstance """ - Update the FlexFlowInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlexFlowPage(self._version, response) - :param unicode friendly_name: A string to describe the resource - :param unicode chat_service_sid: The SID of the chat service - :param FlexFlowInstance.ChannelType channel_type: The channel type - :param unicode contact_identity: The channel contact's Identity - :param bool enabled: Whether the FlexFlow is enabled - :param FlexFlowInstance.IntegrationType integration_type: The integration type - :param unicode integration_flow_sid: The SID of the Flow - :param unicode integration_url: The External Webhook URL - :param unicode integration_workspace_sid: The Workspace SID for a new task - :param unicode integration_workflow_sid: The Workflow SID for a new task - :param unicode integration_channel: task channel for a new task - :param unicode integration_timeout: The task timeout in seconds for a new task - :param unicode integration_priority: The task priority of a new task - :param bool integration_creation_on_message: Whether to create a task when the first message arrives - :param bool long_lived: Reuse this chat channel for future interactions with a contact - :param bool janitor_enabled: Remove active Proxy sessions if the corresponding Task is deleted. - :param unicode integration_retry_count: The number of times to retry the webhook if the first attempt fails + def get(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext - :returns: The updated FlexFlowInstance - :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowInstance + :param sid: The SID of the Flex Flow resource to update. """ - 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, - ) + return FlexFlowContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> FlexFlowContext: """ - Deletes the FlexFlowInstance + Constructs a FlexFlowContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Flex Flow resource to update. """ - return self._proxy.delete() + return FlexFlowContext(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/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 index 11e0e07eb8..46e44fcecd 100644 --- a/twilio/rest/flex_api/v1/web_channel.py +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -1,406 +1,651 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 WebChannelList(ListResource): - """ """ +class WebChannelInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the WebChannelList + class ChatStatus(object): + INACTIVE = "inactive" - :param Version version: Version that contains the resource + """ + :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") + ) - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelList - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelList + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WebChannelContext] = None + + @property + def _proxy(self) -> "WebChannelContext": """ - super(WebChannelList, 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 = '/WebChannels'.format(**self._solution) + :returns: WebChannelContext for this WebChannelInstance + """ + if self._context is None: + self._context = WebChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the WebChannelInstance - :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.flex_api.v1.web_channel.WebChannelInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebChannelInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - Lists WebChannelInstance 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.delete_async() + + def fetch(self) -> "WebChannelInstance": + """ + Fetch the WebChannelInstance - :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.flex_api.v1.web_channel.WebChannelInstance] + :returns: The fetched WebChannelInstance """ - 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) -> "WebChannelInstance": """ - Retrieve a single page of WebChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the WebChannelInstance - :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 WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelPage + :returns: The fetched WebChannelInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Update the WebChannelInstance - return WebChannelPage(self._version, response, self._solution) + :param chat_status: + :param post_engagement_data: The post-engagement data. - def get_page(self, target_url): + :returns: The updated WebChannelInstance """ - Retrieve a specific page of WebChannelInstance records from the API. - Request is executed immediately + return self._proxy.update( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelPage + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, ) - return WebChannelPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def create(self, flex_flow_sid, identity, customer_friendly_name, - chat_friendly_name, chat_unique_name=values.unset, - pre_engagement_data=values.unset): + :returns: Machine friendly representation """ - Create the WebChannelInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode flex_flow_sid: The SID of the FlexFlow - :param unicode identity: The chat identity - :param unicode customer_friendly_name: The chat participant's friendly name - :param unicode chat_friendly_name: The chat channel's friendly name - :param unicode chat_unique_name: The chat channel's unique name - :param unicode pre_engagement_data: The pre-engagement data - :returns: The created WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance +class WebChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - 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, - }) + Initialize the WebChannelContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The SID of the WebChannel resource to update. + """ + super().__init__(version) - return WebChannelInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/WebChannels/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a WebChannelContext + Deletes the WebChannelInstance - :param sid: The SID of the WebChannel resource to fetch - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelContext - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + :returns: True if delete succeeds, False otherwise """ - return WebChannelContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a WebChannelContext + headers = values.of({}) - :param sid: The SID of the WebChannel resource to fetch + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelContext - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + async def delete_async(self) -> bool: """ - return WebChannelContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the WebChannelInstance - 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 WebChannelPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> WebChannelInstance: """ - Initialize the WebChannelPage + Fetch the WebChannelInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelPage - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelPage + :returns: The fetched WebChannelInstance """ - super(WebChannelPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of WebChannelInstance + 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.flex_api.v1.web_channel.WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance - """ - return WebChannelInstance(self._version, payload, ) + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> WebChannelInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the WebChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched WebChannelInstance """ - return '' + headers = values.of({}) -class WebChannelContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the WebChannelContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The SID of the WebChannel resource to fetch + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelContext - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: """ - super(WebChannelContext, self).__init__(version) + Update the WebChannelInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/WebChannels/{sid}'.format(**self._solution) + :param chat_status: + :param post_engagement_data: The post-engagement data. - def fetch(self): + :returns: The updated WebChannelInstance """ - Fetch the WebChannelInstance - :returns: The fetched WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) - return WebChannelInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def update(self, chat_status=values.unset, post_engagement_data=values.unset): + 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: """ - Update the WebChannelInstance + Asynchronous coroutine to update the WebChannelInstance - :param WebChannelInstance.ChatStatus chat_status: The chat status - :param unicode post_engagement_data: The post-engagement data + :param chat_status: + :param post_engagement_data: The post-engagement data. :returns: The updated WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance """ - data = values.of({'ChatStatus': chat_status, 'PostEngagementData': post_engagement_data, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebChannelInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + 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: """ - Deletes the WebChannelInstance + 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 WebChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: + """ + Build an instance of WebChannelInstance + + :param payload: Payload response from the API """ - return self._version.delete(method='DELETE', uri=self._uri, ) + return WebChannelInstance(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 WebChannelInstance(InstanceResource): - """ """ +class WebChannelList(ListResource): - class ChatStatus(object): - INACTIVE = "inactive" + def __init__(self, version: Version): + """ + Initialize the WebChannelList + + :param version: Version that contains the resource - def __init__(self, version, payload, sid=None): """ - Initialize the WebChannelInstance + super().__init__(version) - :returns: twilio.rest.flex_api.v1.web_channel.WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + 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: """ - super(WebChannelInstance, self).__init__(version) + Create the WebChannelInstance - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'flex_flow_sid': payload.get('flex_flow_sid'), - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } + :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"}) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Asynchronously create the WebChannelInstance - :returns: WebChannelContext for this WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelContext + :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 """ - if self._context is None: - self._context = WebChannelContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def account_sid(self): + 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]: """ - :returns: The SID of the Account that created the resource and owns this Workflow - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def flex_flow_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebChannelInstance]: """ - :returns: The SID of the FlexFlow - :rtype: unicode + 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 """ - return self._properties['flex_flow_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[WebChannelInstance]: """ - :returns: The unique string that identifies the WebChannel resource - :rtype: unicode + 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 self._properties['sid'] + 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[WebChannelInstance]: """ - :returns: The absolute URL of the WebChannel resource - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately - @property - def date_created(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 WebChannelInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was 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 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: """ - return self._properties['date_created'] + Asynchronously retrieve a single page of WebChannelInstance 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 WebChannelInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 WebChannelPage(self._version, response) + + def get_page(self, target_url: str) -> WebChannelPage: """ - return self._properties['date_updated'] + Retrieve a specific page of WebChannelInstance 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 WebChannelInstance """ - Fetch the WebChannelInstance + response = self._version.domain.twilio.request("GET", target_url) + return WebChannelPage(self._version, response) - :returns: The fetched WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + async def get_page_async(self, target_url: str) -> WebChannelPage: """ - return self._proxy.fetch() + 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 - def update(self, chat_status=values.unset, post_engagement_data=values.unset): + :returns: Page of WebChannelInstance """ - Update the WebChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebChannelPage(self._version, response) - :param WebChannelInstance.ChatStatus chat_status: The chat status - :param unicode post_engagement_data: The post-engagement data + def get(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext - :returns: The updated WebChannelInstance - :rtype: twilio.rest.flex_api.v1.web_channel.WebChannelInstance + :param sid: The SID of the WebChannel resource to update. """ - return self._proxy.update(chat_status=chat_status, post_engagement_data=post_engagement_data, ) + return WebChannelContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> WebChannelContext: """ - Deletes the WebChannelInstance + Constructs a WebChannelContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the WebChannel resource to update. """ - return self._proxy.delete() + return WebChannelContext(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/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 index 8d4c7aca97..0f1457794c 100644 --- a/twilio/rest/insights/__init__.py +++ b/twilio/rest/insights/__init__.py @@ -1,53 +1,55 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.insights.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Insights Domain - - :returns: Domain for Insights - :rtype: twilio.rest.insights.Insights - """ - super(Insights, self).__init__(twilio) - - self.base_url = 'https://insights.twilio.com' - - # Versions - self._v1 = None - +class Insights(InsightsBase): @property - def v1(self): - """ - :returns: Version v1 of insights - :rtype: twilio.rest.insights.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + def settings(self) -> SettingList: + warn( + "settings is deprecated. Use v1.settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings @property - def calls(self): - """ - :rtype: twilio.rest.insights.v1.call.CallList - """ + def calls(self) -> CallList: + warn( + "calls is deprecated. Use v1.calls instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.calls - def __repr__(self): - """ - Provide a friendly representation + @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 - :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/insights/v1/__init__.py b/twilio/rest/insights/v1/__init__.py index f41a316063..8f7d1946f0 100644 --- a/twilio/rest/insights/v1/__init__.py +++ b/twilio/rest/insights/v1/__init__.py @@ -1,42 +1,75 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Insights - :returns: V1 version of Insights - :rtype: twilio.rest.insights.v1.V1.V1 + :param domain: The Twilio.insights domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._calls = None + 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): - """ - :rtype: twilio.rest.insights.v1.call.CallList - """ + def calls(self) -> CallList: if self._calls is None: self._calls = CallList(self) return self._calls - def __repr__(self): + @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 - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/insights/v1/call/__init__.py b/twilio/rest/insights/v1/call/__init__.py index ddd8d6757a..cb08aa58aa 100644 --- a/twilio/rest/insights/v1/call/__init__.py +++ b/twilio/rest/insights/v1/call/__init__.py @@ -1,304 +1,275 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page +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 -from twilio.rest.insights.v1.call.summary import CallSummaryList -class CallList(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 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 - def __init__(self, version): + @property + def _proxy(self) -> "CallContext": """ - Initialize the CallList - - :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.insights.v1.call.CallList - :rtype: twilio.rest.insights.v1.call.CallList + :returns: CallContext for this CallInstance """ - super(CallList, self).__init__(version) - - # Path Solution - self._solution = {} + if self._context is None: + self._context = CallContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def get(self, sid): + def fetch(self) -> "CallInstance": """ - Constructs a CallContext + Fetch the CallInstance - :param sid: The sid - :returns: twilio.rest.insights.v1.call.CallContext - :rtype: twilio.rest.insights.v1.call.CallContext + :returns: The fetched CallInstance """ - return CallContext(self._version, sid=sid, ) + return self._proxy.fetch() - def __call__(self, sid): + async def fetch_async(self) -> "CallInstance": """ - Constructs a CallContext + Asynchronous coroutine to fetch the CallInstance - :param sid: The sid - :returns: twilio.rest.insights.v1.call.CallContext - :rtype: twilio.rest.insights.v1.call.CallContext + :returns: The fetched CallInstance """ - return CallContext(self._version, sid=sid, ) + return await self._proxy.fetch_async() - def __repr__(self): + @property + def annotation(self) -> AnnotationList: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + Access the annotation """ - return '' + return self._proxy.annotation - -class CallPage(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): + @property + def summary(self) -> CallSummaryList: """ - Initialize the CallPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.insights.v1.call.CallPage - :rtype: twilio.rest.insights.v1.call.CallPage + Access the summary """ - super(CallPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.summary - def get_instance(self, payload): + @property + def events(self) -> EventList: """ - Build an instance of CallInstance - - :param dict payload: Payload response from the API + Access the events + """ + return self._proxy.events - :returns: twilio.rest.insights.v1.call.CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance + @property + def metrics(self) -> MetricList: + """ + Access the metrics """ - return CallInstance(self._version, payload, ) + return self._proxy.metrics - 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 CallContext(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): + def __init__(self, version: Version, sid: str): """ Initialize the CallContext - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.insights.v1.call.CallContext - :rtype: twilio.rest.insights.v1.call.CallContext + :param version: Version that contains the resource + :param sid: """ - super(CallContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Voice/{sid}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Voice/{sid}".format(**self._solution) - # Dependents - self._events = None - self._metrics = None - self._summary = None + self._annotation: Optional[AnnotationList] = None + self._summary: Optional[CallSummaryList] = None + self._events: Optional[EventList] = None + self._metrics: Optional[MetricList] = None - def fetch(self): + def fetch(self) -> CallInstance: """ Fetch the CallInstance - :returns: The fetched CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return CallInstance(self._version, payload, sid=self._solution['sid'], ) - @property - def events(self): + :returns: The fetched CallInstance """ - Access the events - :returns: twilio.rest.insights.v1.call.event.EventList - :rtype: twilio.rest.insights.v1.call.event.EventList - """ - if self._events is None: - self._events = EventList(self._version, call_sid=self._solution['sid'], ) - return self._events + headers = values.of({}) - @property - def metrics(self): - """ - Access the metrics + headers["Accept"] = "application/json" - :returns: twilio.rest.insights.v1.call.metric.MetricList - :rtype: twilio.rest.insights.v1.call.metric.MetricList - """ - if self._metrics is None: - self._metrics = MetricList(self._version, call_sid=self._solution['sid'], ) - return self._metrics + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - @property - def summary(self): - """ - Access the summary + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.insights.v1.call.summary.CallSummaryList - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryList + async def fetch_async(self) -> CallInstance: """ - if self._summary is None: - self._summary = CallSummaryList(self._version, call_sid=self._solution['sid'], ) - return self._summary + Asynchronous coroutine to fetch the CallInstance - def __repr__(self): - """ - Provide a friendly representation - :returns: Machine friendly representation - :rtype: str + :returns: The fetched CallInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class CallInstance(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" - def __init__(self, version, payload, sid=None): - """ - Initialize the CallInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: twilio.rest.insights.v1.call.CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance - """ - super(CallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) @property - def _proxy(self): + def annotation(self) -> AnnotationList: """ - 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.insights.v1.call.CallContext + Access the annotation """ - if self._context is None: - self._context = CallContext(self._version, sid=self._solution['sid'], ) - return self._context + if self._annotation is None: + self._annotation = AnnotationList( + self._version, + self._solution["sid"], + ) + return self._annotation @property - def sid(self): + def summary(self) -> CallSummaryList: """ - :returns: The sid - :rtype: unicode + Access the summary """ - return self._properties['sid'] + if self._summary is None: + self._summary = CallSummaryList( + self._version, + self._solution["sid"], + ) + return self._summary @property - def url(self): + def events(self) -> EventList: """ - :returns: The url - :rtype: unicode + Access the events """ - return self._properties['url'] + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events @property - def links(self): + def metrics(self) -> MetricList: """ - :returns: The links - :rtype: unicode + Access the metrics """ - return self._properties['links'] + if self._metrics is None: + self._metrics = MetricList( + self._version, + self._solution["sid"], + ) + return self._metrics - def fetch(self): + def __repr__(self) -> str: """ - Fetch the CallInstance + Provide a friendly representation - :returns: The fetched CallInstance - :rtype: twilio.rest.insights.v1.call.CallInstance + :returns: Machine friendly representation """ - return self._proxy.fetch() + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def events(self): + +class CallList(ListResource): + + def __init__(self, version: Version): """ - Access the events + Initialize the CallList + + :param version: Version that contains the resource - :returns: twilio.rest.insights.v1.call.event.EventList - :rtype: twilio.rest.insights.v1.call.event.EventList """ - return self._proxy.events + super().__init__(version) - @property - def metrics(self): + def get(self, sid: str) -> CallContext: """ - Access the metrics + Constructs a CallContext - :returns: twilio.rest.insights.v1.call.metric.MetricList - :rtype: twilio.rest.insights.v1.call.metric.MetricList + :param sid: """ - return self._proxy.metrics + return CallContext(self._version, sid=sid) - @property - def summary(self): + def __call__(self, sid: str) -> CallContext: """ - Access the summary + Constructs a CallContext - :returns: twilio.rest.insights.v1.call.summary.CallSummaryList - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryList + :param sid: """ - return self._proxy.summary + return CallContext(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/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 index c37352f13d..98dce5eb71 100644 --- a/twilio/rest/insights/v1/call/event.py +++ b/twilio/rest/insights/v1/call/event.py @@ -1,315 +1,337 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 EventList(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, call_sid): - """ - Initialize the EventList +class EventInstance(InstanceResource): - :param Version version: Version that contains the resource - :param call_sid: The call_sid + class Level(object): + UNKNOWN = "UNKNOWN" + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" - :returns: twilio.rest.insights.v1.call.event.EventList - :rtype: twilio.rest.insights.v1.call.event.EventList - """ - super(EventList, self).__init__(version) + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" - # Path Solution - self._solution = {'call_sid': call_sid, } - self._uri = '/Voice/{call_sid}/Events'.format(**self._solution) + """ + :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 stream(self, edge=values.unset, limit=None, page_size=None): + def __repr__(self) -> str: """ - 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 - :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.insights.v1.call.event.EventInstance] + :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(edge=edge, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) +class EventPage(Page): - def list(self, edge=values.unset, limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 - :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 EventInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.event.EventInstance] + :param payload: Payload response from the API """ - return list(self.stream(edge=edge, limit=limit, page_size=page_size, )) + return EventInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) - def page(self, edge=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 - - :param EventInstance.TwilioEdge edge: The edge - :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 EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventPage + :returns: Machine friendly representation """ - data = values.of({ - 'Edge': edge, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return EventPage(self._version, response, self._solution) +class EventList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, call_sid: str): """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + Initialize the EventList - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. - :returns: Page of EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return EventPage(self._version, response, self._solution) - - def __repr__(self): - """ - Provide a friendly representation + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Events".format(**self._solution) - :returns: Machine friendly representation - :rtype: str + def stream( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: """ - return '' - + 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. -class EventPage(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. """ + :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) - def __init__(self, version, response, solution): + :returns: Generator that will yield up to limit results """ - Initialize the EventPage + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param call_sid: The call_sid + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.insights.v1.call.event.EventPage - :rtype: twilio.rest.insights.v1.call.event.EventPage + async def stream_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: """ - super(EventPage, self).__init__(version, response) + 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. - # Path Solution - self._solution = solution + :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) - def get_instance(self, payload): + :returns: Generator that will yield up to limit results """ - Build an instance of EventInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(edge=edge, page_size=limits["page_size"]) - :param dict payload: Payload response from the API + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.insights.v1.call.event.EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventInstance + def list( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: """ - return EventInstance(self._version, payload, call_sid=self._solution['call_sid'], ) + 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, + ) + ) - def __repr__(self): + async def list_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :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: """ - return '' + 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 -class EventInstance(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. """ + :returns: Page of EventInstance + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - class TwilioEdge(object): - UNKNOWN_EDGE = "unknown_edge" - CARRIER_EDGE = "carrier_edge" - SIP_EDGE = "sip_edge" - SDK_EDGE = "sdk_edge" - CLIENT_EDGE = "client_edge" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class Level(object): - UNKNOWN = "UNKNOWN" - DEBUG = "DEBUG" - INFO = "INFO" - WARNING = "WARNING" - ERROR = "ERROR" + headers["Accept"] = "application/json" - def __init__(self, version, payload, call_sid): - """ - Initialize the EventInstance + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) - :returns: twilio.rest.insights.v1.call.event.EventInstance - :rtype: twilio.rest.insights.v1.call.event.EventInstance + 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: """ - super(EventInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'timestamp': payload.get('timestamp'), - 'call_sid': payload.get('call_sid'), - 'account_sid': payload.get('account_sid'), - 'edge': payload.get('edge'), - 'group': payload.get('group'), - 'level': payload.get('level'), - 'name': payload.get('name'), - 'carrier_edge': payload.get('carrier_edge'), - 'sip_edge': payload.get('sip_edge'), - 'sdk_edge': payload.get('sdk_edge'), - 'client_edge': payload.get('client_edge'), - } - - # Context - self._context = None - self._solution = {'call_sid': call_sid, } + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately - @property - def timestamp(self): - """ - :returns: The timestamp - :rtype: unicode - """ - return self._properties['timestamp'] + :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 - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['call_sid'] + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def edge(self): - """ - :returns: The edge - :rtype: EventInstance.TwilioEdge - """ - return self._properties['edge'] + headers["Accept"] = "application/json" - @property - def group(self): - """ - :returns: The group - :rtype: unicode - """ - return self._properties['group'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) - @property - def level(self): - """ - :returns: The level - :rtype: EventInstance.Level + def get_page(self, target_url: str) -> EventPage: """ - return self._properties['level'] + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def name(self): - """ - :returns: The name - :rtype: unicode - """ - return self._properties['name'] + :param target_url: API-generated URL for the requested results page - @property - def carrier_edge(self): - """ - :returns: The carrier_edge - :rtype: dict + :returns: Page of EventInstance """ - return self._properties['carrier_edge'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) - @property - def sip_edge(self): - """ - :returns: The sip_edge - :rtype: dict + async def get_page_async(self, target_url: str) -> EventPage: """ - return self._properties['sip_edge'] + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def sdk_edge(self): - """ - :returns: The sdk_edge - :rtype: dict - """ - return self._properties['sdk_edge'] + :param target_url: API-generated URL for the requested results page - @property - def client_edge(self): - """ - :returns: The client_edge - :rtype: dict + :returns: Page of EventInstance """ - return self._properties['client_edge'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(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/insights/v1/call/metric.py b/twilio/rest/insights/v1/call/metric.py index da5b3c24d4..77f770ae7c 100644 --- a/twilio/rest/insights/v1/call/metric.py +++ b/twilio/rest/insights/v1/call/metric.py @@ -1,303 +1,352 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 MetricList(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 MetricInstance(InstanceResource): - def __init__(self, version, call_sid): - """ - Initialize the MetricList + class StreamDirection(object): + UNKNOWN = "unknown" + INBOUND = "inbound" + OUTBOUND = "outbound" + BOTH = "both" - :param Version version: Version that contains the resource - :param call_sid: The call_sid + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" - :returns: twilio.rest.insights.v1.call.metric.MetricList - :rtype: twilio.rest.insights.v1.call.metric.MetricList - """ - super(MetricList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'call_sid': call_sid, } - self._uri = '/Voice/{call_sid}/Metrics'.format(**self._solution) + self._solution = { + "call_sid": call_sid, + } - def stream(self, edge=values.unset, direction=values.unset, limit=None, - page_size=None): + def __repr__(self) -> str: """ - 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 - :param MetricInstance.StreamDirection 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) + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.metric.MetricInstance] + :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(edge=edge, direction=direction, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) +class MetricPage(Page): - def list(self, edge=values.unset, direction=values.unset, limit=None, - page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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 - :param MetricInstance.StreamDirection 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) + Build an instance of MetricInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.insights.v1.call.metric.MetricInstance] + :param payload: Payload response from the API """ - return list(self.stream(edge=edge, direction=direction, limit=limit, page_size=page_size, )) + return MetricInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) - def page(self, edge=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 MetricInstance records from the API. - Request is executed immediately - - :param MetricInstance.TwilioEdge edge: The edge - :param MetricInstance.StreamDirection 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 + Provide a friendly representation - :returns: Page of MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricPage + :returns: Machine friendly representation """ - data = values.of({ - 'Edge': edge, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return MetricPage(self._version, response, self._solution) +class MetricList(ListResource): - def get_page(self, target_url): + def __init__(self, version: Version, call_sid: str): """ - Retrieve a specific page of MetricInstance records from the API. - Request is executed immediately + Initialize the MetricList - :param str target_url: API-generated URL for the requested results page + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. - :returns: Page of MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return MetricPage(self._version, response, self._solution) + super().__init__(version) - def __repr__(self): - """ - Provide a friendly representation + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Metrics".format(**self._solution) - :returns: Machine friendly representation - :rtype: str + 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]: """ - return '' - + 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. -class MetricPage(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. """ + :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) - def __init__(self, version, response, solution): + :returns: Generator that will yield up to limit results """ - Initialize the MetricPage + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, direction=direction, page_size=limits["page_size"]) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param call_sid: The call_sid + return self._version.stream(page, limits["limit"]) - :returns: twilio.rest.insights.v1.call.metric.MetricPage - :rtype: twilio.rest.insights.v1.call.metric.MetricPage + 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]: """ - super(MetricPage, self).__init__(version, response) + 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. - # Path Solution - self._solution = solution + :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) - def get_instance(self, payload): + :returns: Generator that will yield up to limit results """ - Build an instance of MetricInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) - :param dict payload: Payload response from the API + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.insights.v1.call.metric.MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricInstance + 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]: """ - return MetricInstance(self._version, payload, call_sid=self._solution['call_sid'], ) + 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, + ) + ) - def __repr__(self): + 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]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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: """ - return '' + 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 -class MetricInstance(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. """ + :returns: Page of MetricInstance + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - class TwilioEdge(object): - UNKNOWN_EDGE = "unknown_edge" - CARRIER_EDGE = "carrier_edge" - SIP_EDGE = "sip_edge" - SDK_EDGE = "sdk_edge" - CLIENT_EDGE = "client_edge" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class StreamDirection(object): - UNKNOWN = "unknown" - INBOUND = "inbound" - OUTBOUND = "outbound" - BOTH = "both" + headers["Accept"] = "application/json" - def __init__(self, version, payload, call_sid): - """ - Initialize the MetricInstance + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) - :returns: twilio.rest.insights.v1.call.metric.MetricInstance - :rtype: twilio.rest.insights.v1.call.metric.MetricInstance + 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: """ - super(MetricInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'timestamp': payload.get('timestamp'), - 'call_sid': payload.get('call_sid'), - 'account_sid': payload.get('account_sid'), - 'edge': payload.get('edge'), - 'direction': payload.get('direction'), - 'carrier_edge': payload.get('carrier_edge'), - 'sip_edge': payload.get('sip_edge'), - 'sdk_edge': payload.get('sdk_edge'), - 'client_edge': payload.get('client_edge'), - } + Asynchronously retrieve a single page of MetricInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'call_sid': call_sid, } + :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 - @property - def timestamp(self): - """ - :returns: The timestamp - :rtype: unicode + :returns: Page of MetricInstance """ - return self._properties['timestamp'] + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_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 edge(self): - """ - :returns: The edge - :rtype: MetricInstance.TwilioEdge - """ - return self._properties['edge'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) - @property - def direction(self): + def get_page(self, target_url: str) -> MetricPage: """ - :returns: The direction - :rtype: MetricInstance.StreamDirection - """ - return self._properties['direction'] + Retrieve a specific page of MetricInstance records from the API. + Request is executed immediately - @property - def carrier_edge(self): - """ - :returns: The carrier_edge - :rtype: dict - """ - return self._properties['carrier_edge'] + :param target_url: API-generated URL for the requested results page - @property - def sip_edge(self): - """ - :returns: The sip_edge - :rtype: dict + :returns: Page of MetricInstance """ - return self._properties['sip_edge'] + response = self._version.domain.twilio.request("GET", target_url) + return MetricPage(self._version, response, self._solution) - @property - def sdk_edge(self): + async def get_page_async(self, target_url: str) -> MetricPage: """ - :returns: The sdk_edge - :rtype: dict - """ - return self._properties['sdk_edge'] + Asynchronously retrieve a specific page of MetricInstance records from the API. + Request is executed immediately - @property - def client_edge(self): - """ - :returns: The client_edge - :rtype: dict + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance """ - return self._properties['client_edge'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return MetricPage(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/insights/v1/call/summary.py b/twilio/rest/insights/v1/call/summary.py deleted file mode 100644 index 11b53de517..0000000000 --- a/twilio/rest/insights/v1/call/summary.py +++ /dev/null @@ -1,399 +0,0 @@ -# coding=utf-8 -r""" -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 CallSummaryList(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, call_sid): - """ - Initialize the CallSummaryList - - :param Version version: Version that contains the resource - :param call_sid: The call_sid - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryList - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryList - """ - super(CallSummaryList, self).__init__(version) - - # Path Solution - self._solution = {'call_sid': call_sid, } - - def get(self): - """ - Constructs a CallSummaryContext - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryContext - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryContext - """ - return CallSummaryContext(self._version, call_sid=self._solution['call_sid'], ) - - def __call__(self): - """ - Constructs a CallSummaryContext - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryContext - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryContext - """ - return CallSummaryContext(self._version, call_sid=self._solution['call_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CallSummaryPage(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 CallSummaryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param call_sid: The call_sid - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryPage - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryPage - """ - super(CallSummaryPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CallSummaryInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryInstance - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryInstance - """ - return CallSummaryInstance(self._version, payload, call_sid=self._solution['call_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CallSummaryContext(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, call_sid): - """ - Initialize the CallSummaryContext - - :param Version version: Version that contains the resource - :param call_sid: The call_sid - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryContext - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryContext - """ - super(CallSummaryContext, self).__init__(version) - - # Path Solution - self._solution = {'call_sid': call_sid, } - self._uri = '/Voice/{call_sid}/Summary'.format(**self._solution) - - def fetch(self, processing_state=values.unset): - """ - Fetch the CallSummaryInstance - - :param CallSummaryInstance.ProcessingState processing_state: The processing_state - - :returns: The fetched CallSummaryInstance - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryInstance - """ - data = values.of({'ProcessingState': processing_state, }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - - return CallSummaryInstance(self._version, payload, 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 CallSummaryInstance(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 CallType(object): - CARRIER = "carrier" - SIP = "sip" - TRUNKING = "trunking" - CLIENT = "client" - - class CallState(object): - RINGING = "ringing" - COMPLETED = "completed" - BUSY = "busy" - FAIL = "fail" - NOANSWER = "noanswer" - CANCELED = "canceled" - ANSWERED = "answered" - UNDIALED = "undialed" - - class ProcessingState(object): - COMPLETE = "complete" - PARTIAL = "partial" - - def __init__(self, version, payload, call_sid): - """ - Initialize the CallSummaryInstance - - :returns: twilio.rest.insights.v1.call.summary.CallSummaryInstance - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryInstance - """ - super(CallSummaryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'call_sid': payload.get('call_sid'), - 'call_type': payload.get('call_type'), - 'call_state': payload.get('call_state'), - 'processing_state': payload.get('processing_state'), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'duration': deserialize.integer(payload.get('duration')), - 'connect_duration': deserialize.integer(payload.get('connect_duration')), - 'from_': payload.get('from'), - 'to': payload.get('to'), - 'carrier_edge': payload.get('carrier_edge'), - 'client_edge': payload.get('client_edge'), - 'sdk_edge': payload.get('sdk_edge'), - 'sip_edge': payload.get('sip_edge'), - 'tags': payload.get('tags'), - 'url': payload.get('url'), - 'attributes': payload.get('attributes'), - 'properties': payload.get('properties'), - } - - # Context - self._context = None - self._solution = {'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: CallSummaryContext for this CallSummaryInstance - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryContext - """ - if self._context is None: - self._context = CallSummaryContext(self._version, 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 call_sid(self): - """ - :returns: The call_sid - :rtype: unicode - """ - return self._properties['call_sid'] - - @property - def call_type(self): - """ - :returns: The call_type - :rtype: CallSummaryInstance.CallType - """ - return self._properties['call_type'] - - @property - def call_state(self): - """ - :returns: The call_state - :rtype: CallSummaryInstance.CallState - """ - return self._properties['call_state'] - - @property - def processing_state(self): - """ - :returns: The processing_state - :rtype: CallSummaryInstance.ProcessingState - """ - return self._properties['processing_state'] - - @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 connect_duration(self): - """ - :returns: The connect_duration - :rtype: unicode - """ - return self._properties['connect_duration'] - - @property - def from_(self): - """ - :returns: The from - :rtype: dict - """ - return self._properties['from_'] - - @property - def to(self): - """ - :returns: The to - :rtype: dict - """ - return self._properties['to'] - - @property - def carrier_edge(self): - """ - :returns: The carrier_edge - :rtype: dict - """ - return self._properties['carrier_edge'] - - @property - def client_edge(self): - """ - :returns: The client_edge - :rtype: dict - """ - return self._properties['client_edge'] - - @property - def sdk_edge(self): - """ - :returns: The sdk_edge - :rtype: dict - """ - return self._properties['sdk_edge'] - - @property - def sip_edge(self): - """ - :returns: The sip_edge - :rtype: dict - """ - return self._properties['sip_edge'] - - @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 attributes(self): - """ - :returns: The attributes - :rtype: dict - """ - return self._properties['attributes'] - - @property - def properties(self): - """ - :returns: The properties - :rtype: dict - """ - return self._properties['properties'] - - def fetch(self, processing_state=values.unset): - """ - Fetch the CallSummaryInstance - - :param CallSummaryInstance.ProcessingState processing_state: The processing_state - - :returns: The fetched CallSummaryInstance - :rtype: twilio.rest.insights.v1.call.summary.CallSummaryInstance - """ - return self._proxy.fetch(processing_state=processing_state, ) - - 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/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 68c2bae06f..61158f8e6a 100644 --- a/twilio/rest/ip_messaging/__init__.py +++ b/twilio/rest/ip_messaging/__init__.py @@ -1,72 +1,25 @@ -# coding=utf-8 -r""" -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://chat.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 bb7eea6a04..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 e029b459f8..4aa6d3fc63 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -1,454 +1,711 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class CredentialInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CredentialList + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - :returns: twilio.rest.chat.v1.credential.CredentialList - :rtype: twilio.rest.chat.v1.credential.CredentialList + @property + def _proxy(self) -> "CredentialContext": """ - super(CredentialList, 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 = '/Credentials'.format(**self._solution) + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the CredentialInstance - :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.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 await self._proxy.delete_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) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v1.credential.CredentialInstance] + + :returns: The fetched CredentialInstance """ - 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) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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: The fetched CredentialInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return CredentialPage(self._version, response, self._solution) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The updated CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Create the CredentialInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param CredentialInstance.PushService type: The type of push-notification service the credential is for - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + Initialize the CredentialContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) - return CredentialInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CredentialContext + Deletes the CredentialInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + :returns: True if delete succeeds, False otherwise """ - return CredentialContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CredentialContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + async def delete_async(self) -> bool: """ - return CredentialContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CredentialInstance - 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 CredentialPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialPage + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.chat.v1.credential.CredentialPage - :rtype: twilio.rest.chat.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - super(CredentialPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of CredentialInstance + 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.v1.credential.CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialInstance """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the CredentialContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v1.credential.CredentialContext - :rtype: twilio.rest.chat.v1.credential.CredentialContext + 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: """ - super(CredentialContext, self).__init__(version) + Update the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def fetch(self): + :returns: The updated CredentialInstance """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v1.credential.CredentialInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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: """ - Update the CredentialInstance + Asynchronous coroutine to update the CredentialInstance - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: :returns: The 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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the CredentialInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'sandbox': payload.get('sandbox'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: """ - return self._properties['sid'] + Create the CredentialInstance - @property - def account_sid(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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 """ - 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 = 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 string that you assigned to describe the resource - :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 of push-notification service the credential is for - :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: [APN only] Whether to send the credential to sandbox APNs - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the Credential 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 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 the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: The 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: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 0e102ed45f..3a77cf765e 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -1,913 +1,1359 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 the ServiceInstance + Deletes the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :returns: The 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(method='POST', uri=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']) - - 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": """ - 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.chat.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 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 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: Page of ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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: - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + 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, + ) - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + @property + def channels(self) -> ChannelList: """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): + Access the channels """ - Constructs a ServiceContext + return self._proxy.channels - :param sid: The unique string that identifies the resource + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles - :returns: twilio.rest.chat.v1.service.ServiceContext - :rtype: twilio.rest.chat.v1.service.ServiceContext + @property + def users(self) -> UserList: + """ + 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 unique string that identifies the resource - :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 the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of WebHook events that are enabled for this Service instance - :param unicode webhooks_on_message_send_url: The URL of the webhook to call in response to the on_message_send event - :param unicode webhooks_on_message_send_method: The HTTP method to use when calling the webhooks.on_message_send.url - :param unicode webhooks_on_message_update_url: The URL of the webhook to call in response to the on_message_update event - :param unicode webhooks_on_message_update_method: The HTTP method to use when calling the webhooks.on_message_update.url - :param unicode webhooks_on_message_remove_url: The URL of the webhook to call in response to the on_message_remove event - :param unicode webhooks_on_message_remove_method: The HTTP method to use when calling the webhooks.on_message_remove.url - :param unicode webhooks_on_channel_add_url: The URL of the webhook to call in response to the on_channel_add event - :param unicode webhooks_on_channel_add_method: The HTTP method to use when calling the webhooks.on_channel_add.url - :param unicode webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the on_channel_destroy event - :param unicode webhooks_on_channel_destroy_method: The HTTP method to use when calling the webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_update_url: The URL of the webhook to call in response to the on_channel_update event - :param unicode webhooks_on_channel_update_method: The HTTP method to use when calling the webhooks.on_channel_update.url - :param unicode webhooks_on_member_add_url: The URL of the webhook to call in response to the on_member_add event - :param unicode webhooks_on_member_add_method: The HTTP method to use when calling the webhooks.on_member_add.url - :param unicode webhooks_on_member_remove_url: The URL of the webhook to call in response to the on_member_remove event - :param unicode webhooks_on_member_remove_method: The HTTP method to use when calling the webhooks.on_member_remove.url - :param unicode webhooks_on_message_sent_url: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_sent_method: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_updated_url: The URL of the webhook to call in response to the on_message_updated event - :param unicode webhooks_on_message_updated_method: The HTTP method to use when calling the webhooks.on_message_updated.url - :param unicode webhooks_on_message_removed_url: The URL of the webhook to call in response to the on_message_removed event - :param unicode webhooks_on_message_removed_method: The HTTP method to use when calling the webhooks.on_message_removed.url - :param unicode webhooks_on_channel_added_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_added_method: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_method: The HTTP method to use when calling the webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_updated_url: he URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_channel_updated_method: The HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_added_url: The URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_member_added_method: he HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_removed_url: The URL of the webhook to call in response to the on_member_removed event - :param unicode webhooks_on_member_removed_method: The HTTP method to use when calling the webhooks.on_member_removed.url - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: :returns: The updated ServiceInstance - :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.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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def channels(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'default_service_role_sid': payload.get('default_service_role_sid'), - 'default_channel_role_sid': payload.get('default_channel_role_sid'), - 'default_channel_creator_role_sid': payload.get('default_channel_creator_role_sid'), - 'read_status_enabled': payload.get('read_status_enabled'), - 'reachability_enabled': payload.get('reachability_enabled'), - 'typing_indicator_timeout': deserialize.integer(payload.get('typing_indicator_timeout')), - 'consumption_report_interval': deserialize.integer(payload.get('consumption_report_interval')), - 'limits': payload.get('limits'), - 'webhooks': payload.get('webhooks'), - 'pre_webhook_url': payload.get('pre_webhook_url'), - 'post_webhook_url': payload.get('post_webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'webhook_filters': payload.get('webhook_filters'), - 'notifications': payload.get('notifications'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 service role assigned to users when they are added to the service - :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 channel role assigned to users when they are added to a channel - :rtype: unicode - """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The channel role assigned to a channel creator when they join a new channel - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is 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: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: - @property - def typing_indicator_timeout(self): - """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :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: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def webhooks(self): - """ - :returns: An object that contains information about the webhooks configured for this service - :rtype: dict - """ - return self._properties['webhooks'] + headers["Accept"] = "application/json" - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :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 URL for post-event webhooks - :rtype: unicode - """ - return self._properties['post_webhook_url'] + return ServiceInstance(self._version, payload) - @property - def webhook_method(self): - """ - :returns: The HTTP method to use for both PRE and POST webhooks - :rtype: unicode + async def create_async(self, friendly_name: str) -> ServiceInstance: """ - return self._properties['webhook_method'] + Asynchronously create the ServiceInstance - @property - def webhook_filters(self): + :param friendly_name: + + :returns: The created ServiceInstance """ - :returns: The list of WebHook events that are enabled for this Service instance - :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 notification configuration for the Service instance - :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 absolute URL of the Service 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: The absolute URLs of the Service's Channels, Roles, and Users - :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 the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.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, + } + ) + + 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 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"}) + + 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_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_update_url=values.unset, - webhooks_on_message_update_method=values.unset, - webhooks_on_message_remove_url=values.unset, - webhooks_on_message_remove_method=values.unset, - webhooks_on_channel_add_url=values.unset, - webhooks_on_channel_add_method=values.unset, - webhooks_on_channel_destroy_url=values.unset, - webhooks_on_channel_destroy_method=values.unset, - webhooks_on_channel_update_url=values.unset, - webhooks_on_channel_update_method=values.unset, - webhooks_on_member_add_url=values.unset, - webhooks_on_member_add_method=values.unset, - webhooks_on_member_remove_url=values.unset, - webhooks_on_member_remove_method=values.unset, - webhooks_on_message_sent_url=values.unset, - webhooks_on_message_sent_method=values.unset, - webhooks_on_message_updated_url=values.unset, - webhooks_on_message_updated_method=values.unset, - webhooks_on_message_removed_url=values.unset, - webhooks_on_message_removed_method=values.unset, - webhooks_on_channel_added_url=values.unset, - webhooks_on_channel_added_method=values.unset, - webhooks_on_channel_destroyed_url=values.unset, - webhooks_on_channel_destroyed_method=values.unset, - webhooks_on_channel_updated_url=values.unset, - webhooks_on_channel_updated_method=values.unset, - webhooks_on_member_added_url=values.unset, - webhooks_on_member_added_method=values.unset, - webhooks_on_member_removed_url=values.unset, - webhooks_on_member_removed_method=values.unset, - limits_channel_members=values.unset, - limits_user_channels=values.unset): + 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 friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of WebHook events that are enabled for this Service instance - :param unicode webhooks_on_message_send_url: The URL of the webhook to call in response to the on_message_send event - :param unicode webhooks_on_message_send_method: The HTTP method to use when calling the webhooks.on_message_send.url - :param unicode webhooks_on_message_update_url: The URL of the webhook to call in response to the on_message_update event - :param unicode webhooks_on_message_update_method: The HTTP method to use when calling the webhooks.on_message_update.url - :param unicode webhooks_on_message_remove_url: The URL of the webhook to call in response to the on_message_remove event - :param unicode webhooks_on_message_remove_method: The HTTP method to use when calling the webhooks.on_message_remove.url - :param unicode webhooks_on_channel_add_url: The URL of the webhook to call in response to the on_channel_add event - :param unicode webhooks_on_channel_add_method: The HTTP method to use when calling the webhooks.on_channel_add.url - :param unicode webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the on_channel_destroy event - :param unicode webhooks_on_channel_destroy_method: The HTTP method to use when calling the webhooks.on_channel_destroy.url - :param unicode webhooks_on_channel_update_url: The URL of the webhook to call in response to the on_channel_update event - :param unicode webhooks_on_channel_update_method: The HTTP method to use when calling the webhooks.on_channel_update.url - :param unicode webhooks_on_member_add_url: The URL of the webhook to call in response to the on_member_add event - :param unicode webhooks_on_member_add_method: The HTTP method to use when calling the webhooks.on_member_add.url - :param unicode webhooks_on_member_remove_url: The URL of the webhook to call in response to the on_member_remove event - :param unicode webhooks_on_member_remove_method: The HTTP method to use when calling the webhooks.on_member_remove.url - :param unicode webhooks_on_message_sent_url: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_sent_method: The URL of the webhook to call in response to the on_message_sent event - :param unicode webhooks_on_message_updated_url: The URL of the webhook to call in response to the on_message_updated event - :param unicode webhooks_on_message_updated_method: The HTTP method to use when calling the webhooks.on_message_updated.url - :param unicode webhooks_on_message_removed_url: The URL of the webhook to call in response to the on_message_removed event - :param unicode webhooks_on_message_removed_method: The HTTP method to use when calling the webhooks.on_message_removed.url - :param unicode webhooks_on_channel_added_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_added_method: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the on_channel_added event - :param unicode webhooks_on_channel_destroyed_method: The HTTP method to use when calling the webhooks.on_channel_destroyed.url - :param unicode webhooks_on_channel_updated_url: he URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_channel_updated_method: The HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_added_url: The URL of the webhook to call in response to the on_channel_updated event - :param unicode webhooks_on_member_added_method: he HTTP method to use when calling the webhooks.on_channel_updated.url - :param unicode webhooks_on_member_removed_url: The URL of the webhook to call in response to the on_member_removed event - :param unicode webhooks_on_member_removed_method: The HTTP method to use when calling the webhooks.on_member_removed.url - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service + :param target_url: API-generated URL for the requested results page - :returns: The 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_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, - ) + 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 31404b15d7..14423c9e38 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -1,598 +1,790 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the ChannelList +class ChannelInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - :returns: twilio.rest.chat.v1.service.channel.ChannelList - :rtype: twilio.rest.chat.v1.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - def create(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, type=values.unset): + @property + def _proxy(self) -> "ChannelContext": """ - Create the ChannelInstance - - :param unicode friendly_name: A string to describe the new resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param ChannelInstance.ChannelType type: The visibility of the channel + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance + :returns: ChannelContext for this ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - 'Type': type, - }) + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete(self) -> bool: + """ + 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. - - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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.channel.ChannelInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ChannelInstance - page = self.page(type=type, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, type=values.unset, limit=None, page_size=None): + def fetch(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. + Fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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 self._proxy.fetch() - def page(self, type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "ChannelInstance": """ - Retrieve a single page of ChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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.v1.service.channel.ChannelPage + :returns: The fetched ChannelInstance """ - data = values.of({ - 'Type': serialize.map(type, lambda e: e), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - return ChannelPage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 specific page of ChannelInstance records from the API. - Request is executed immediately + 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 self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, ) - return ChannelPage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a ChannelContext + Asynchronous coroutine to update the ChannelInstance - :param sid: The unique string that identifies the resource + :param friendly_name: + :param unique_name: + :param attributes: - :returns: twilio.rest.chat.v1.service.channel.ChannelContext - :rtype: twilio.rest.chat.v1.service.channel.ChannelContext + :returns: The updated ChannelInstance """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) - def __call__(self, sid): + @property + def invites(self) -> InviteList: """ - Constructs a ChannelContext + Access the invites + """ + return self._proxy.invites - :param sid: The unique string that identifies the resource + @property + def members(self) -> MemberList: + """ + 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 SID of the Service that the resource is associated with + 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 SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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 the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data + :param friendly_name: + :param unique_name: + :param attributes: :returns: The updated ChannelInstance - :rtype: twilio.rest.chat.v1.service.channel.ChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Attributes': attributes, - }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'attributes': payload.get('attributes'), - 'type': payload.get('type'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('created_by'), - 'members_count': deserialize.integer(payload.get('members_count')), - 'messages_count': deserialize.integer(payload.get('messages_count')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :param friendly_name: + :param unique_name: + :param attributes: + :param type: - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Accept"] = "application/json" - @property - def type(self): - """ - :returns: The visibility of the channel. Can be: `public` or `private` - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Asynchronously create the ChannelInstance - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :rtype: unicode - """ - return self._properties['created_by'] + :param friendly_name: + :param unique_name: + :param attributes: + :param type: - @property - def members_count(self): - """ - :returns: The number of Members in the Channel - :rtype: unicode + :returns: The created ChannelInstance """ - 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 number of Messages in the Channel - :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 absolute URL of the Channel resource - :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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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. - def fetch(self): + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Fetch the ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :returns: The 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"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - def delete(self): + 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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset): + 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: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data + :param target_url: API-generated URL for the requested results page - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v1.service.channel.member.MemberList - :rtype: twilio.rest.chat.v1.service.channel.member.MemberList + :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 0fa7a2dacb..d348540346 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -1,448 +1,598 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[InviteContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + :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 the InviteInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + return self._proxy.delete() - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) - 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` value of the resources to read - :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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The unique string that identifies the resource - :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 unique string that identifies the resource - :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 + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v1.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v1.service.channel.invite.InvitePage + def __repr__(self) -> str: """ - super(InvitePage, 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 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The unique string that identifies the resource + :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 the InviteInstance + Create the InviteInstance - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v1.service.channel.invite.InviteInstance + :param identity: + :param role_sid: + + :returns: The created InviteInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: """ - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'created_by': payload.get('created_by'), - 'url': payload.get('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): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Channel the new resource belongs to - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 SID of the Role assigned to the member - :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 identity of the User that created the invite - :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 absolute URL of the Invite resource - :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 the InviteInstance + Constructs a InviteContext - :returns: The 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 85e875f574..26a68650ef 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -1,496 +1,716 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[MemberContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel for the member + :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 the MemberInstance + return self._proxy.delete() - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role to assign to the member + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) + :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` value of the resources to read - :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 await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + 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 MemberInstance 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` value of the resources to read - :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.v1.service.channel.member.MemberPage +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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) -> 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 - :returns: Page of MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return MemberPage(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 MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.service.channel.member.MemberContext - :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext + :returns: True if delete succeeds, False otherwise """ - return MemberContext( + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - 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 unique string that identifies the resource - :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" - def __init__(self, version, response, solution): + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: """ - 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 SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel for the member + :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 +class MemberPage(Page): - :returns: twilio.rest.chat.v1.service.channel.member.MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + 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 SID of the Service to fetch the resource from - :param channel_sid: The unique ID of the channel the member belongs to - :param sid: The unique string that identifies the resource + :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 the MemberInstance + Create the MemberInstance - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v1.service.channel.member.MemberInstance + :param identity: + :param role_sid: + + :returns: The created MemberInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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 SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The 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(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload.get('last_consumption_timestamp')), - 'url': payload.get('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): - """ - :returns: The unique string that identifies the resource - :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 SID of the Account that created the resource - :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 unique ID of the Channel for the member - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the member - :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 index of the last Message that the Member has read within the Channel - :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 ISO 8601 based timestamp string that represents the date-time of the last Message read event for the Member within the Channel - :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 absolute URL of the Member resource - :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 the MemberInstance + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - :returns: The 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 SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext - :returns: The 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 f039cd35ce..ad7c05d8a1 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -1,513 +1,731 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MessageList + class OrderType(object): + ASC = "asc" + DESC = "desc" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel the Message resource belongs to + """ + :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") - :returns: twilio.rest.chat.v1.service.channel.message.MessageList - :rtype: twilio.rest.chat.v1.service.channel.message.MessageList + 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": """ - super(MessageList, 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, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, body, from_=values.unset, attributes=values.unset): + def delete(self) -> bool: """ - Create the MessageInstance + Deletes the MessageInstance - :param unicode body: The message to send to the channel - :param unicode from_: The identity of the new message's author - :param unicode attributes: A valid JSON string that contains application-specific data - :returns: The 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 self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - 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 - :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.channel.message.MessageInstance] + def fetch(self) -> "MessageInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the MessageInstance - page = self.page(order=order, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() - def list(self, order=values.unset, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.message.MessageInstance] + :returns: The fetched MessageInstance """ - return list(self.stream(order=order, limit=limit, page_size=page_size, )) + return await self._proxy.fetch_async() - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Update the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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 body: + :param attributes: - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return MessagePage(self._version, response, self._solution) + return self._proxy.update( + body=body, + attributes=attributes, + ) - def get_page(self, target_url): + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the MessageInstance - :param str target_url: API-generated URL for the requested results page + :param body: + :param attributes: - :returns: Page of MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + body=body, + attributes=attributes, ) - return MessagePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a MessageContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext - """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, - ) +class MessageContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - Constructs a MessageContext - - :param sid: The unique string that identifies the resource + Initialize the MessageContext - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) ) - def __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the MessageInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class MessagePage(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 MessagePage + Asynchronous coroutine that deletes the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The unique ID of the Channel the Message resource belongs to - :returns: twilio.rest.chat.v1.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v1.service.channel.message.MessagePage + :returns: True if delete succeeds, False otherwise """ - super(MessagePage, 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) -> MessageInstance: """ - Build an instance of MessageInstance + Fetch the MessageInstance - :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 + :returns: The fetched MessageInstance """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + 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 MessageContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, channel_sid, sid): + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Initialize the MessageContext + Update the MessageInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param channel_sid: The unique ID of the Channel the message to fetch belongs to - :param sid: The unique string that identifies the resource + :param body: + :param attributes: - :returns: twilio.rest.chat.v1.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v1.service.channel.message.MessageContext + :returns: The updated MessageInstance """ - super(MessageContext, self).__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) + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Fetch the MessageInstance + Asynchronous coroutine to update the MessageInstance - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + :param body: + :param attributes: + + :returns: The updated MessageInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the MessageInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def update(self, body=values.unset, attributes=values.unset): - """ - Update the MessageInstance - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data +class MessagePage(Page): - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: """ - data = values.of({'Body': body, 'Attributes': attributes, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class MessageInstance(InstanceResource): - """ """ +class MessageList(ListResource): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'attributes': payload.get('attributes'), - 'service_sid': payload.get('service_sid'), - 'to': payload.get('to'), - 'channel_sid': payload.get('channel_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'was_edited': payload.get('was_edited'), - 'from_': payload.get('from'), - 'body': payload.get('body'), - 'index': deserialize.integer(payload.get('index')), - 'url': payload.get('url'), - } + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - # Context - self._context = None + """ + super().__init__(version) + + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - @property - def _proxy(self): + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the MessageInstance - :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'], - ) - return self._context + :param body: + :param from_: + :param attributes: - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers["Accept"] = "application/json" - @property - def to(self): - """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode - """ - return self._properties['to'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def channel_sid(self): - """ - :returns: The unique ID of the Channel the Message resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: """ - return self._properties['date_created'] + Asynchronously create the MessageInstance - @property - def date_updated(self): + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - return self._properties['date_updated'] + 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 was_edited(self): + :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 """ - :returns: Whether the message has been edited since it was created - :rtype: bool + 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]: """ - return self._properties['was_edited'] + 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 from_(self): + :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 """ - :returns: The identity of the message's author - :rtype: unicode + 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]: """ - return self._properties['from_'] + 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 body(self): + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - :returns: The content of the message - :rtype: unicode + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: """ - return self._properties['body'] + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def index(self): + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance """ - :returns: The index of the message within the Channel - :rtype: unicode + 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: """ - return self._properties['index'] + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately - @property - def url(self): + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance """ - :returns: The absolute URL of the Message resource - :rtype: unicode + 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: """ - return self._properties['url'] + 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 fetch(self): + :returns: Page of MessageInstance """ - Fetch the MessageInstance + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) - :returns: The 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 message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext - :returns: The 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 7101ac6971..d5d0628032 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -1,442 +1,645 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the RoleList +class RoleInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :returns: twilio.rest.chat.v1.service.role.RoleList - :rtype: twilio.rest.chat.v1.service.role.RoleList - """ - super(RoleList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None - def create(self, friendly_name, type, permission): + @property + def _proxy(self) -> "RoleContext": """ - Create the RoleInstance - - :param unicode friendly_name: A string to describe the new resource - :param RoleInstance.RoleType type: The type of role - :param unicode permission: A permission the role should have + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance + :returns: RoleContext for this RoleInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the RoleInstance - :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.role.RoleInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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 that deletes 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: 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) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The fetched RoleInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RolePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RoleInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RolePage + :returns: The fetched RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RolePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Update the RoleInstance - :param sid: The unique string that identifies the resource + :param permission: - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update( + permission=permission, + ) - def __call__(self, sid): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance - :param sid: The unique string that identifies the resource + :param permission: - :returns: twilio.rest.chat.v1.service.role.RoleContext - :rtype: twilio.rest.chat.v1.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + permission=permission, + ) - 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 RolePage(Page): - """ """ +class RoleContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the RolePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the RoleContext - :returns: twilio.rest.chat.v1.service.role.RolePage - :rtype: twilio.rest.chat.v1.service.role.RolePage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(RolePage, 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}/Roles/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RoleInstance + Deletes 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: True if delete succeeds, False otherwise """ - return RoleInstance(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 RoleInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RoleContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> RoleInstance: """ - Initialize the RoleContext + Fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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 = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: """ - Fetch the RoleInstance + Asynchronous coroutine to fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param permission: + + :returns: The updated RoleInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, permission): + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Update the RoleInstance + Asynchronous coroutine to update the RoleInstance - :param unicode permission: A permission the role should have + :param permission: :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v1.service.role.RoleInstance """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'permissions': payload.get('permissions'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 string that you assigned to describe the resource - :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 of role - :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: An array of the permissions the role has been granted - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the Role 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance """ - Fetch the RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: The 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: A permission the role should have + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: The 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 aa5a20360b..5f37f2d3aa 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -1,521 +1,723 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + 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 the UserInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the new resource + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The 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(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 unique string that identifies the resource + :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 unique string that identifies the resource - - :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 SID of the Service that the resource is associated with + 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 SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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" - # Dependents - self._user_channels = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: """ - Fetch the UserInstance + Asynchronous coroutine to fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource + :param role_sid: + :param attributes: + :param friendly_name: :returns: The updated UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'attributes': payload.get('attributes'), - 'friendly_name': payload.get('friendly_name'), - 'role_sid': payload.get('role_sid'), - 'identity': payload.get('identity'), - 'is_online': payload.get('is_online'), - 'is_notifiable': payload.get('is_notifiable'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'joined_channels_count': deserialize.integer(payload.get('joined_channels_count')), - 'links': payload.get('links'), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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 SID of the assigned to the user - :rtype: unicode - """ - return self._properties['role_sid'] + :param version: Version that contains the resource + :param service_sid: - @property - def identity(self): """ - :returns: The string that identifies the resource's User - :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: Whether the User is actively connected to the Service instance and 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: Whether the User has a potentially valid Push Notification registration for the Service instance - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 number of Channels this User is a Member of - :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 absolute URLs of the Channel and Binding resources related to the user - :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 absolute URL of the User 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 = 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 - 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 UserInstance """ - Fetch the UserInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v1.service.user.UserInstance + headers = values.of({"Content-Type": "application/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: """ - 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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext - :returns: The 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 76750d6987..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,273 +1,322 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with - :param user_sid: The unique string that identifies the resource + 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']) +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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return "" - response = self._version.page(method='GET', uri=self._uri, params=data, ) - 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 SID of the Service that the resource is associated with - :param user_sid: The unique string that identifies the 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: 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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'member_sid': payload.get('member_sid'), - 'status': payload.get('status'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'unread_messages_count': deserialize.integer(payload.get('unread_messages_count')), - 'links': payload.get('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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + headers["Accept"] = "application/json" - @property - def member_sid(self): - """ - :returns: The SID of the User as a Member in the Channel - :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 of the User on the Channel - :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 index of the last Message in the Channel the Member has read - :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 number of unread Messages in the Channel for the User - :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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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 c39ed02e28..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 261e47d3c3..065c5048e9 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -1,454 +1,711 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class CredentialInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CredentialList + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - :returns: twilio.rest.chat.v2.credential.CredentialList - :rtype: twilio.rest.chat.v2.credential.CredentialList + @property + def _proxy(self) -> "CredentialContext": """ - super(CredentialList, 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 = '/Credentials'.format(**self._solution) + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the CredentialInstance - :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.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 await self._proxy.delete_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) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.credential.CredentialInstance] + + :returns: The fetched CredentialInstance """ - 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) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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: The fetched CredentialInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return CredentialPage(self._version, response, self._solution) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The updated CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Create the CredentialInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param CredentialInstance.PushService type: The type of push-notification service the credential is for - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console - :returns: The created CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + Initialize the CredentialContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) - return CredentialInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CredentialContext + Deletes the CredentialInstance - :param sid: The SID of the Credential resource to fetch - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + :returns: True if delete succeeds, False otherwise """ - return CredentialContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CredentialContext + headers = values.of({}) - :param sid: The SID of the Credential resource to fetch + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + async def delete_async(self) -> bool: """ - return CredentialContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CredentialInstance - 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 CredentialPage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> CredentialInstance: """ - Initialize the CredentialPage + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.chat.v2.credential.CredentialPage - :rtype: twilio.rest.chat.v2.credential.CredentialPage + :returns: The fetched CredentialInstance """ - super(CredentialPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of CredentialInstance + 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.credential.CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialInstance """ - return '' + headers = values.of({}) -class CredentialContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, sid): - """ - Initialize the CredentialContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The SID of the Credential resource to fetch + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.credential.CredentialContext - :rtype: twilio.rest.chat.v2.credential.CredentialContext + 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: """ - super(CredentialContext, self).__init__(version) + Update the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: - def fetch(self): + :returns: The updated CredentialInstance """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.chat.v2.credential.CredentialInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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: """ - Update the CredentialInstance + Asynchronous coroutine to update the CredentialInstance - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: :returns: The 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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the CredentialInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'sandbox': payload.get('sandbox'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: """ - return self._properties['sid'] + Create the CredentialInstance - @property - def account_sid(self): + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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 """ - 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 = 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 string that you assigned to describe the resource - :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 of push-notification service the credential is for - :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: [APN only] Whether to send the credential to sandbox APNs - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Credential 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 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 the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: The 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: A string to describe the resource - :param unicode certificate: [APN only] The URL encoded representation of the certificate - :param unicode private_key: [APN only] The URL encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode 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 unicode secret: [FCM only] The Server key of your project from Firebase console + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 2ac876450e..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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,799 +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 the ServiceInstance - - :param unicode friendly_name: A string to describe the resource + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=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']) + :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": """ - 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.chat.v2.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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 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 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: Page of ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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: - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The SID of the Service resource to fetch + 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, + ) - :returns: twilio.rest.chat.v2.service.ServiceContext - :rtype: twilio.rest.chat.v2.service.ServiceContext + @property + def bindings(self) -> BindingList: """ - return ServiceContext(self._version, sid=sid, ) + Access the bindings + """ + return self._proxy.bindings - def __call__(self, sid): + @property + def channels(self) -> ChannelList: """ - Constructs a ServiceContext + Access the channels + """ + return self._proxy.channels - :param sid: The SID of the Service resource to fetch + @property + def roles(self) -> RoleList: + """ + 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: + """ + 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.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 of the Service resource to fetch - :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 the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.chat.v2.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param unicode notifications_new_message_sound: The name of the sound to play when a new message is added to a channel - :param bool notifications_new_message_badge_count_enabled: Whether the new message badge is enabled - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param unicode notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param unicode notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of webhook events that are enabled for this Service instance - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service - :param unicode media_compatibility_message: The message to send when a media message has no text - :param unicode pre_webhook_retry_count: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :param unicode post_webhook_retry_count: The number of times calls to the `post_webhook_url` will be retried - :param bool notifications_log_enabled: Whether to log notifications + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: :returns: The updated ServiceInstance - :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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'default_service_role_sid': payload.get('default_service_role_sid'), - 'default_channel_role_sid': payload.get('default_channel_role_sid'), - 'default_channel_creator_role_sid': payload.get('default_channel_creator_role_sid'), - 'read_status_enabled': payload.get('read_status_enabled'), - 'reachability_enabled': payload.get('reachability_enabled'), - 'typing_indicator_timeout': deserialize.integer(payload.get('typing_indicator_timeout')), - 'consumption_report_interval': deserialize.integer(payload.get('consumption_report_interval')), - 'limits': payload.get('limits'), - 'pre_webhook_url': payload.get('pre_webhook_url'), - 'post_webhook_url': payload.get('post_webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'webhook_filters': payload.get('webhook_filters'), - 'pre_webhook_retry_count': deserialize.integer(payload.get('pre_webhook_retry_count')), - 'post_webhook_retry_count': deserialize.integer(payload.get('post_webhook_retry_count')), - 'notifications': payload.get('notifications'), - 'media': payload.get('media'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 service role assigned to users when they are added to the service - :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 channel role assigned to users when they are added to a channel - :rtype: unicode """ - return self._properties['default_channel_role_sid'] + super().__init__(version) - @property - def default_channel_creator_role_sid(self): - """ - :returns: The channel role assigned to a channel creator when they join a new channel - :rtype: unicode - """ - return self._properties['default_channel_creator_role_sid'] + self._uri = "/Services" - @property - def read_status_enabled(self): - """ - :returns: Whether the Message Consumption Horizon feature is 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: Whether the Reachability Indicator feature is enabled for this Service instance - :rtype: bool - """ - return self._properties['reachability_enabled'] + :param friendly_name: - @property - def typing_indicator_timeout(self): - """ - :returns: How long in seconds to wait before assuming the user is no longer typing - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['typing_indicator_timeout'] - @property - def consumption_report_interval(self): - """ - :returns: DEPRECATED - :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: An object that describes the limits of the service instance - :rtype: dict - """ - return self._properties['limits'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def pre_webhook_url(self): - """ - :returns: The webhook URL for pre-event webhooks - :rtype: unicode - """ - return self._properties['pre_webhook_url'] + headers["Accept"] = "application/json" - @property - def post_webhook_url(self): - """ - :returns: The URL for post-event webhooks - :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 HTTP method to use for both PRE and POST webhooks - :rtype: unicode - """ - return self._properties['webhook_method'] + return ServiceInstance(self._version, payload) - @property - def webhook_filters(self): - """ - :returns: The list of webhook events that are enabled for this Service instance - :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: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :rtype: unicode - """ - return self._properties['pre_webhook_retry_count'] + :param friendly_name: - @property - def post_webhook_retry_count(self): - """ - :returns: The number of times calls to the `post_webhook_url` will be retried - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['post_webhook_retry_count'] - @property - def notifications(self): - """ - :returns: The notification configuration for the Service instance - :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 properties of the media that the service supports - :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 absolute URL of the Service resource - :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 absolute URLs of the Service's Channels, Roles, and Users - :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. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 fetch(self): + :returns: list that will contain up to limit results """ - Fetch the ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: The 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" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) - 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): + async def 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 friendly_name: A string to describe the resource - :param unicode default_service_role_sid: The service role assigned to users when they are added to the service - :param unicode default_channel_role_sid: The channel role assigned to users when they are added to a channel - :param unicode default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel - :param bool read_status_enabled: Whether to enable the Message Consumption Horizon feature - :param bool reachability_enabled: Whether to enable the Reachability Indicator feature for this Service instance - :param unicode typing_indicator_timeout: How long in seconds to wait before assuming the user is no longer typing - :param unicode consumption_report_interval: DEPRECATED - :param bool notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel - :param unicode notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel - :param unicode notifications_new_message_sound: The name of the sound to play when a new message is added to a channel - :param bool notifications_new_message_badge_count_enabled: Whether the new message badge is enabled - :param bool notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel - :param unicode notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel - :param unicode notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel - :param bool notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel - :param unicode notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed - :param unicode notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel - :param bool notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel - :param unicode notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel - :param unicode notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel - :param unicode pre_webhook_url: The webhook URL for pre-event webhooks - :param unicode post_webhook_url: The URL for post-event webhooks - :param unicode webhook_method: The HTTP method to use for both PRE and POST webhooks - :param unicode webhook_filters: The list of webhook events that are enabled for this Service instance - :param unicode limits_channel_members: The maximum number of Members that can be added to Channels within this Service - :param unicode limits_user_channels: The maximum number of Channels Users can be a Member of within this Service - :param unicode media_compatibility_message: The message to send when a media message has no text - :param unicode pre_webhook_retry_count: Count of times webhook will be retried in case of timeout or 429/503/504 HTTP responses - :param unicode post_webhook_retry_count: The number of times calls to the `post_webhook_url` will be retried - :param bool notifications_log_enabled: Whether to log notifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList + :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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList + :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 7c1c078ce1..af9018af9f 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -1,438 +1,536 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the Binding resource is associated with + 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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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']) + :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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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 push technology used by the Binding resources to read - :param unicode identity: The `identity` value of the resources to read - :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 """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 of the resource to fetch +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 of the resource to fetch + # 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 SID of the Service that the Binding resource is associated with - :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({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> BindingInstance: """ - Build an instance of BindingInstance + Fetch the BindingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.chat.v2.service.binding.BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance + :returns: The fetched BindingInstance """ - return BindingInstance(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 BindingContext(InstanceContext): - """ """ + return BindingInstance( + 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) -> BindingInstance: """ - Initialize the BindingContext + Asynchronous coroutine to fetch the BindingInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the resource to fetch - :returns: twilio.rest.chat.v2.service.binding.BindingContext - :rtype: twilio.rest.chat.v2.service.binding.BindingContext + :returns: The fetched BindingInstance """ - super(BindingContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Bindings/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the BindingInstance + headers["Accept"] = "application/json" - :returns: The fetched BindingInstance - :rtype: twilio.rest.chat.v2.service.binding.BindingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=self._uri, ) + 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, 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 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'endpoint': payload.get('endpoint'), - 'identity': payload.get('identity'), - 'credential_sid': payload.get('credential_sid'), - 'binding_type': payload.get('binding_type'), - 'message_types': payload.get('message_types'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the Binding resource is associated with - :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 ISO 8601 date and time in GMT when the resource was 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, + 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - 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 unique endpoint identifier for the Binding - :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 string that identifies the resource's User - :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 SID of the Credential for the binding - :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 push technology to use for the binding - :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 Programmable Chat message types the binding is subscribed to - :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 absolute URL of the Binding resource - :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 absolute URLs of the Binding's User - :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 the BindingInstance + Constructs a BindingContext - :returns: The 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 868781e892..8220a4be9c 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -1,17 +1,24 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -19,648 +26,937 @@ from twilio.rest.ip_messaging.v2.service.channel.webhook import WebhookList -class ChannelList(ListResource): - """ """ +class ChannelInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the ChannelList + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.channel.ChannelList - :rtype: twilio.rest.chat.v2.service.channel.ChannelList - """ - super(ChannelList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Channels'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None - 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, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "ChannelContext": """ - Create the ChannelInstance - - :param unicode friendly_name: A string to describe the new resource - :param unicode unique_name: An application-defined string that uniquely identifies the Channel resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param ChannelInstance.ChannelType type: The visibility of the channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :returns: ChannelContext for this 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, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) - - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, type=values.unset, limit=None, page_size=None): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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. + Deletes the ChannelInstance - :param ChannelInstance.ChannelType type: The visibility of the channel to read - :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 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 """ - 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']) + 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 visibility of the channel to read - :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 visibility of the channel to read - :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance - :param 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 friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: - :returns: Page of ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelPage + :returns: The updated ChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ChannelPage(self._version, response, self._solution) + 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: - def get(self, sid): + :returns: The updated ChannelInstance """ - Constructs a ChannelContext - - :param sid: The SID of the resource + 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: + """ + 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 + Access the members + """ + return self._proxy.members - :param sid: The SID of the resource + @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: + """ + Access the webhooks """ - return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + 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 SID of the Service that the resource is associated with + 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 - - def get_instance(self, payload): - """ - Build an instance of ChannelInstance + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None - :returns: twilio.rest.chat.v2.service.channel.ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - return ChannelInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the ChannelInstance - def __repr__(self): - """ - Provide a friendly representation + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: Machine friendly representation - :rtype: str + :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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, sid): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Initialize the ChannelContext + Asynchronous coroutine that deletes the ChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the resource + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: twilio.rest.chat.v2.service.channel.ChannelContext - :rtype: twilio.rest.chat.v2.service.channel.ChannelContext + :returns: True if delete succeeds, False otherwise """ - super(ChannelContext, self).__init__(version) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Channels/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._members = None - self._messages = None - self._invites = None - self._webhooks = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ChannelInstance: """ Fetch the ChannelInstance + :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) return ChannelInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def fetch_async(self) -> ChannelInstance: """ - Deletes the ChannelInstance + Asynchronous coroutine to fetch the ChannelInstance - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: The fetched ChannelInstance """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, unique_name=values.unset, - attributes=values.unset, date_created=values.unset, - date_updated=values.unset, created_by=values.unset, - x_twilio_webhook_enabled=values.unset): + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: """ Update the ChannelInstance - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: :returns: The updated ChannelInstance - :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 = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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'], + 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): - """ - Access the invites - - :returns: twilio.rest.chat.v2.service.channel.invite.InviteList - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteList - """ - if self._invites is None: - self._invites = InviteList( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['sid'], - ) - return self._invites - - @property - def webhooks(self): + def webhooks(self) -> WebhookList: """ Access the webhooks - - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList """ 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._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) - + 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" - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" - - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'attributes': payload.get('attributes'), - 'type': payload.get('type'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('created_by'), - 'members_count': deserialize.integer(payload.get('members_count')), - 'messages_count': deserialize.integer(payload.get('messages_count')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] +class ChannelList(ListResource): - @property - def unique_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + Initialize the ChannelList - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + :param version: Version that contains the resource + :param service_sid: - @property - def type(self): """ - :returns: The visibility of the channel. Can be: `public` or `private` - :rtype: ChannelInstance.ChannelType - """ - return self._properties['type'] + super().__init__(version) - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + # 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: """ - return self._properties['date_created'] + Create the ChannelInstance - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + :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: - @property - def created_by(self): - """ - :returns: The identity of the User that created the channel - :rtype: unicode + :returns: The created ChannelInstance """ - return self._properties['created_by'] - @property - def members_count(self): - """ - :returns: The number of Members in the Channel - :rtype: unicode - """ - return self._properties['members_count'] + 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 messages_count(self): - """ - :returns: The number of Messages that have been passed in the Channel - :rtype: unicode + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance """ - return self._properties['messages_count'] - @property - def url(self): + 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 absolute URL of the Channel resource - :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['url'] + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) - @property - def links(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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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['links'] + 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 fetch(self): + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: """ - Fetch the 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. - :returns: The fetched ChannelInstance - :rtype: twilio.rest.chat.v2.service.channel.ChannelInstance + :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._proxy.fetch() + 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. - def delete(self, x_twilio_webhook_enabled=values.unset): + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: """ - Deletes the ChannelInstance + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of ChannelInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) - 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, - x_twilio_webhook_enabled=values.unset): + 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: """ - Update the ChannelInstance + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode created_by: The identity of the User that created the Channel - :param ChannelInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: The 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def members(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 ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: """ - Access the members + 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: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + :returns: Page of ChannelInstance """ - return self._proxy.members + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def messages(self): + async def get_page_async(self, target_url: str) -> ChannelPage: """ - Access the messages + 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: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList + :returns: Page of ChannelInstance """ - return self._proxy.messages + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) - @property - def invites(self): + def get(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 + ) - @property - def webhooks(self): + def __call__(self, sid: str) -> ChannelContext: """ - Access the webhooks + Constructs a ChannelContext - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + :param sid: """ - return self._proxy.webhooks + 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 2cfc3f6d89..4fa3c187fc 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -1,448 +1,598 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - 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[InviteContext] = None + + @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 SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + :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 the InviteInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The Role assigned to the new member + return self._proxy.delete() - :returns: The 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(method='POST', uri=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` value of the resources to read - :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']) - 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` value of the resources to read - :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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a InviteContext + Asynchronous coroutine that deletes the InviteInstance - :param sid: The SID of the Invite resource to fetch - :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 of the Invite resource to fetch - :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 + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the new resource belongs to + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.channel.invite.InvitePage - :rtype: twilio.rest.chat.v2.service.channel.invite.InvitePage + def __repr__(self) -> str: """ - super(InvitePage, 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 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The SID of the Invite resource to fetch + :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 the InviteInstance + Create the InviteInstance - :returns: The fetched InviteInstance - :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance + :param identity: + :param role_sid: + + :returns: The created InviteInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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" - def __init__(self, version, payload, service_sid, channel_sid, sid=None): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: """ - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'created_by': payload.get('created_by'), - 'url': payload.get('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): + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the Account that created the resource - :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 SID of the Channel the new resource belongs to - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 SID of the Role assigned to the member - :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 identity of the User that created the invite - :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 absolute URL of the Invite resource - :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 the InviteInstance + Constructs a InviteContext - :returns: The 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 9ca747da47..6456d3be20 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -1,563 +1,905 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MemberList + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel for the member + """ + :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 - :returns: twilio.rest.chat.v2.service.channel.member.MemberList - :rtype: twilio.rest.chat.v2.service.channel.member.MemberList + @property + def _proxy(self) -> "MemberContext": """ - super(MemberList, 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, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Members'.format(**self._solution) + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context - def 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Create the MemberInstance + Deletes the MemberInstance - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last Message in the Channel the Member has read - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :returns: The created MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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, }) + Asynchronous coroutine that deletes the MemberInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return MemberInstance( - 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( + 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` value of the resources to read - :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']) - 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() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance - :param unicode identity: The `identity` value of the resources to read - :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 + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.member.MemberInstance] + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance """ - return list(self.stream(identity=identity, limit=limit, page_size=page_size, )) + 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` value of the resources to read - :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): """ - data = 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(method='GET', uri=self._uri, params=data, ) + :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({}) - 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[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MemberContext + Asynchronous coroutine that deletes the MemberInstance - :param sid: The SID of the Member resource to fetch + :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( + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( self._version, - 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 of the Member resource to fetch - :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 = 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, + 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: """ - Provide a friendly representation + Update the MemberInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + 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({}) -class MemberPage(Page): - """ """ + 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"], + ) - def __init__(self, version, response, solution): + 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 """ - Initialize the MemberPage - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel for the member + 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" - :returns: twilio.rest.chat.v2.service.channel.member.MemberPage - :rtype: twilio.rest.chat.v2.service.channel.member.MemberPage + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: """ - super(MemberPage, 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 MemberPage(Page): - def get_instance(self, payload): + 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the channel the member belongs to - :param sid: The SID of the Member resource to fetch + :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): + 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: """ - Fetch the MemberInstance + Create the MemberInstance - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) return MemberInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self, x_twilio_webhook_enabled=values.unset): - """ - Deletes the MemberInstance - - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The created MemberInstance """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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", + } + ) - 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): - """ - Update the MemberInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the Member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + headers["Accept"] = "application/json" - :returns: The 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), - 'Attributes': attributes, - }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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): - """ """ + 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. - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + :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) - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'channel_sid': payload.get('channel_sid'), - 'service_sid': payload.get('service_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'role_sid': payload.get('role_sid'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'last_consumption_timestamp': deserialize.iso8601_datetime(payload.get('last_consumption_timestamp')), - 'url': payload.get('url'), - 'attributes': payload.get('attributes'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) - # 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, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: MemberContext for this MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberContext - """ - 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'], + :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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Channel for the member - :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 SID of the Service that the resource is associated with - :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 string that identifies the resource's User - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the member - :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 index of the last Message that the Member has read within the Channel - :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 ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel - :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: The absolute URL of the Member resource - :rtype: unicode + :returns: Page of MemberInstance """ - return self._properties['url'] + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers = values.of({"Content-Type": "application/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 fetch(self): + def get_page(self, target_url: str) -> MemberPage: """ - Fetch the MemberInstance + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :returns: The fetched MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) - def delete(self, x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> MemberPage: """ - Deletes the MemberInstance + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of MemberInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) - 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, attributes=values.unset, - x_twilio_webhook_enabled=values.unset): + def get(self, sid: str) -> MemberContext: """ - Update the MemberInstance + Constructs a MemberContext - :param unicode role_sid: The SID of the Role to assign to the member - :param unicode last_consumed_message_index: The index of the last consumed Message for the Channel for the Member - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string representing the datetime of the last Message read event for the Member within the Channel - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode attributes: A valid JSON string that contains application-specific data - :param MemberInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :returns: The updated MemberInstance - :rtype: twilio.rest.chat.v2.service.channel.member.MemberInstance + def __call__(self, sid: str) -> MemberContext: """ - 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, - attributes=attributes, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + 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 03c46f9d84..838b3c7271 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -1,600 +1,905 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - def __init__(self, version, service_sid, channel_sid): - """ - Initialize the MessageList + class OrderType(object): + ASC = "asc" + DESC = "desc" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.channel.message.MessageList - :rtype: twilio.rest.chat.v2.service.channel.message.MessageList - """ - super(MessageList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'channel_sid': channel_sid, } - self._uri = '/Services/{service_sid}/Channels/{channel_sid}/Messages'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None - 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, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "MessageContext": """ - Create the MessageInstance + 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 from_: The Identity of the new message's author - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message - :param unicode body: The message to send to the channel - :param unicode media_sid: The Media Sid to be attached to the new Message - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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: The created MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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, }) + Deletes the MessageInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - return MessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) - def stream(self, order=values.unset, limit=None, page_size=None): + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - 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. + Asynchronous coroutine that deletes the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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 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.message.MessageInstance] + :returns: True if delete succeeds, False otherwise """ - 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']) + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) - def list(self, order=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.channel.message.MessageInstance] + :returns: The fetched MessageInstance """ - return list(self.stream(order=order, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, order=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "MessageInstance": """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the MessageInstance - :param MessageInstance.OrderType order: The sort order of the returned messages - :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.chat.v2.service.channel.message.MessagePage + :returns: The fetched MessageInstance """ - data = values.of({ - 'Order': order, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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_: - return MessagePage(self._version, response, self._solution) - - def get_page(self, target_url): + :returns: The updated MessageInstance """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately + 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_, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: The updated MessageInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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_, ) - return MessagePage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a MessageContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The SID of the Message resource to fetch +class MessageContext(InstanceContext): - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ - return MessageContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=sid, + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) ) - def __call__(self, sid): + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: """ - Constructs a MessageContext + Deletes the MessageInstance - :param sid: The SID of the Message resource to fetch + :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, + } ) - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronous coroutine that deletes the MessageInstance - :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 MessagePage(Page): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, response, solution): + def fetch(self) -> MessageInstance: """ - Initialize the MessagePage + Fetch the MessageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param channel_sid: The SID of the Channel the Message resource belongs to - :returns: twilio.rest.chat.v2.service.channel.message.MessagePage - :rtype: twilio.rest.chat.v2.service.channel.message.MessagePage + :returns: The fetched MessageInstance """ - super(MessagePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of MessageInstance + 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.channel.message.MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ 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"], + 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 MessageContext(InstanceContext): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, service_sid, channel_sid, sid): - """ - Initialize the MessageContext + 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 SID of the Service to fetch the resource from - :param channel_sid: The SID of the Channel the message to fetch belongs to - :param sid: The SID of the Message resource to fetch + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.chat.v2.service.channel.message.MessageContext - :rtype: twilio.rest.chat.v2.service.channel.message.MessageContext + 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: """ - super(MessageContext, self).__init__(version) + Update the MessageInstance - # 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) + :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_: - def fetch(self): + :returns: The updated MessageInstance """ - Fetch the MessageInstance - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return MessageInstance( self._version, payload, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def delete(self, x_twilio_webhook_enabled=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 """ - Deletes the MessageInstance - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + 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 - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, from_=values.unset, - x_twilio_webhook_enabled=values.unset): - """ - Update the MessageInstance + headers["Accept"] = "application/json" - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable - :param unicode from_: The Identity of the message's author - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + 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: """ - 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({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) + Provide a friendly representation - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + :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, - 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 __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 MessageInstance(InstanceResource): - """ """ +class MessageList(ListResource): - class OrderType(object): - ASC = "asc" - DESC = "desc" + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'attributes': payload.get('attributes'), - 'service_sid': payload.get('service_sid'), - 'to': payload.get('to'), - 'channel_sid': payload.get('channel_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'last_updated_by': payload.get('last_updated_by'), - 'was_edited': payload.get('was_edited'), - 'from_': payload.get('from'), - 'body': payload.get('body'), - 'index': deserialize.integer(payload.get('index')), - 'type': payload.get('type'), - 'media': payload.get('media'), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'channel_sid': channel_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "channel_sid": channel_sid, } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the MessageInstance - :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'], - ) - return self._context + :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: - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created MessageInstance """ - return self._properties['sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + 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", + } + ) - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers["Accept"] = "application/json" - @property - def to(self): - """ - :returns: The SID of the Channel that the message was sent to - :rtype: unicode - """ - return self._properties['to'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the Message resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + 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: - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + :returns: The created MessageInstance """ - return self._properties['date_updated'] - @property - def last_updated_by(self): - """ - :returns: The Identity of the User who last updated the Message - :rtype: unicode - """ - return self._properties['last_updated_by'] + 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", + } + ) - @property - def was_edited(self): - """ - :returns: Whether the message has been edited since it was created - :rtype: bool - """ - return self._properties['was_edited'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def from_(self): - """ - :returns: The Identity of the message's author - :rtype: unicode - """ - return self._properties['from_'] + headers["Accept"] = "application/json" - @property - def body(self): + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: """ - :returns: The content of the message - :rtype: unicode + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['body'] + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) - @property - def index(self): + 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]: """ - :returns: The index of the message within the Channel - :rtype: unicode + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['index'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) - @property - def type(self): + 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]: """ - :returns: The Message type - :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 "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: """ - return self._properties['type'] + 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 media(self): + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: """ - :returns: A Media object that describes the Message's media if attached; otherwise, null - :rtype: dict + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance """ - return self._properties['media'] + data = values.of( + { + "Order": order, + "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 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: """ - :returns: The absolute URL of the Message resource - :rtype: unicode + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance """ - return self._properties['url'] + 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 fetch(self): + def get_page(self, target_url: str) -> MessagePage: """ - Fetch the MessageInstance + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :returns: The fetched MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.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 delete(self, x_twilio_webhook_enabled=values.unset): + async def get_page_async(self, target_url: str) -> MessagePage: """ - Deletes the MessageInstance + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of MessageInstance """ - return self._proxy.delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) - def update(self, body=values.unset, attributes=values.unset, - date_created=values.unset, date_updated=values.unset, - last_updated_by=values.unset, from_=values.unset, - x_twilio_webhook_enabled=values.unset): + def get(self, sid: str) -> MessageContext: """ - Update the MessageInstance + Constructs a MessageContext - :param unicode body: The message to send to the channel - :param unicode attributes: A valid JSON string that contains application-specific data - :param datetime date_created: The ISO 8601 date and time in GMT when the resource was created - :param datetime date_updated: The ISO 8601 date and time in GMT when the resource was updated - :param unicode last_updated_by: The Identity of the User who last updated the Message, if applicable - :param unicode from_: The Identity of the message's author - :param MessageInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) - :returns: The updated MessageInstance - :rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance + def __call__(self, sid: str) -> MessageContext: """ - return self._proxy.update( - body=body, - attributes=attributes, - date_created=date_created, - date_updated=date_updated, - last_updated_by=last_updated_by, - from_=from_, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def __repr__(self): + 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 index 36674d986a..3c7570fd0e 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/webhook.py +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -1,524 +1,800 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 WebhookList(ListResource): - """ """ +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") + ) - 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[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": """ - Initialize the WebhookList + 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 SID of the Service that the Channel Webhook resource is associated with - :param channel_sid: The SID of the Channel the Channel Webhook resource belongs to + :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 - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookList - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookList + def delete(self) -> bool: """ - super(WebhookList, self).__init__(version) + Deletes the WebhookInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 WebhookInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.webhook.WebhookInstance] + + :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) -> "WebhookInstance": + """ + Fetch the WebhookInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + 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) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.channel.webhook.WebhookInstance] + + :returns: The fetched WebhookInstance """ - 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, + 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": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + Update the WebhookInstance - :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 configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: - :returns: Page of WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: The updated WebhookInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + 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, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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: - return WebhookPage(self._version, response, self._solution) + :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 get_page(self, target_url): + def __repr__(self) -> str: """ - Retrieve a specific page of WebhookInstance 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 WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + +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: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the WebhookInstance + - def create(self, type, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the WebhookInstance - :param WebhookInstance.Type type: The type of webhook - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + headers = values.of({}) - :returns: The created WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + 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 """ - 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, - }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> WebhookInstance: """ - Constructs a WebhookContext + Asynchronous coroutine to fetch the WebhookInstance - :param sid: The SID of the Channel Webhook resource to fetch - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :returns: The fetched WebhookInstance """ - return WebhookContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( 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): + 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: """ - Constructs a WebhookContext + Update the WebhookInstance - :param sid: The SID of the Channel Webhook resource to fetch + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :returns: The updated WebhookInstance """ - return WebhookContext( + + 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, - 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): - """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :returns: The updated WebhookInstance """ - return '' + 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({}) -class WebhookPage(Page): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the WebhookPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Channel Webhook resource is associated with - :param channel_sid: The SID of the Channel the Channel Webhook resource belongs to + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookPage - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookPage + :returns: Machine friendly representation """ - super(WebhookPage, 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 WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: """ Build an instance of WebhookInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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'], + 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 WebhookContext(InstanceContext): - """ """ +class WebhookList(ListResource): - def __init__(self, version, service_sid, channel_sid, sid): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ - Initialize the WebhookContext + Initialize the WebhookList - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service with the Channel to fetch the Webhook resource from - :param channel_sid: The SID of the Channel the resource to fetch belongs to - :param sid: The SID of the Channel Webhook resource to fetch + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookContext - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext """ - super(WebhookContext, 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}/Webhooks/{sid}'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) - def fetch(self): + 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: """ - Fetch the WebhookInstance + Create the WebhookInstance - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + 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 """ - Update the WebhookInstance - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + 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"}) - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.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["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): - """ - Deletes the WebhookInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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. - def __repr__(self): - """ - Provide a friendly representation + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class WebhookInstance(InstanceResource): - """ """ - - class Type(object): - WEBHOOK = "webhook" - TRIGGER = "trigger" - STUDIO = "studio" + 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. - class Method(object): - GET = "GET" - POST = "POST" + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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): + :returns: Generator that will yield up to limit results """ - Initialize the WebhookInstance + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - super(WebhookInstance, self).__init__(version) + Lists WebhookInstance 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'type': payload.get('type'), - 'url': payload.get('url'), - 'configuration': payload.get('configuration'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 = { - 'service_sid': service_sid, - 'channel_sid': channel_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[WebhookInstance]: """ - 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 WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - channel_sid=self._solution['channel_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 unique string that identifies the resource - :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, + ) -> WebhookPage: """ - return self._properties['sid'] + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 service_sid(self): - """ - :returns: The SID of the Service that the Channel Webhook resource is associated with - :rtype: unicode + :returns: Page of WebhookInstance """ - return self._properties['service_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the Channel Webhook resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def type(self): - """ - :returns: The type of webhook - :rtype: unicode - """ - return self._properties['type'] + headers["Accept"] = "application/json" - @property - def url(self): - """ - :returns: The absolute URL of the Channel Webhook resource - :rtype: unicode - """ - return self._properties['url'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) - @property - def configuration(self): - """ - :returns: The JSON string that describes the configuration object for the channel webhook - :rtype: dict + async def 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: """ - return self._properties['configuration'] + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the 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: Page of WebhookInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: """ - return self._properties['date_updated'] + 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 - def fetch(self): + :returns: Page of WebhookInstance """ - Fetch the WebhookInstance + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :returns: The fetched WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + async def get_page_async(self, target_url: str) -> WebhookPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately - def update(self, configuration_url=values.unset, - configuration_method=values.unset, - configuration_filters=values.unset, - configuration_triggers=values.unset, - configuration_flow_sid=values.unset, - configuration_retry_count=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance """ - Update the WebhookInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) - :param unicode configuration_url: The URL of the webhook to call - :param WebhookInstance.Method configuration_method: The HTTP method used to call `configuration.url` - :param unicode configuration_filters: The events that cause us to call the Channel Webhook - :param unicode configuration_triggers: A string that will cause us to call the webhook when it is found in a message body - :param unicode configuration_flow_sid: The SID of the Studio Flow to call when an event occurs - :param unicode configuration_retry_count: The number of times to retry the webhook if the first attempt fails + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext - :returns: The updated WebhookInstance - :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance + :param sid: """ - 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, + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, ) - def delete(self): + def __call__(self, sid: str) -> WebhookContext: """ - Deletes the WebhookInstance + Constructs a WebhookContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: """ - return self._proxy.delete() + return WebhookContext( + 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/role.py b/twilio/rest/ip_messaging/v2/service/role.py index 27b461b3ba..32f70c2272 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -1,442 +1,645 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the RoleList +class RoleInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" - :returns: twilio.rest.chat.v2.service.role.RoleList - :rtype: twilio.rest.chat.v2.service.role.RoleList - """ - super(RoleList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Roles'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None - def create(self, friendly_name, type, permission): + @property + def _proxy(self) -> "RoleContext": """ - Create the RoleInstance - - :param unicode friendly_name: A string to describe the new resource - :param RoleInstance.RoleType type: The type of role - :param unicode permission: A permission the role should have + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance + :returns: RoleContext for this RoleInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Permission': serialize.map(permission, lambda e: e), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the RoleInstance - :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.role.RoleInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._proxy.delete() - def list(self, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - 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 that deletes 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: 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) -> "RoleInstance": """ - Retrieve a single page of RoleInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The fetched RoleInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RolePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "RoleInstance": """ - Retrieve a specific page of RoleInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RoleInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RolePage + :returns: The fetched RoleInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return RolePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Update the RoleInstance - :param sid: The SID of the Role resource to fetch + :param permission: - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update( + permission=permission, + ) - def __call__(self, sid): + async def update_async(self, permission: List[str]) -> "RoleInstance": """ - Constructs a RoleContext + Asynchronous coroutine to update the RoleInstance - :param sid: The SID of the Role resource to fetch + :param permission: - :returns: twilio.rest.chat.v2.service.role.RoleContext - :rtype: twilio.rest.chat.v2.service.role.RoleContext + :returns: The updated RoleInstance """ - return RoleContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + permission=permission, + ) - 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 RolePage(Page): - """ """ +class RoleContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the RolePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the RoleContext - :returns: twilio.rest.chat.v2.service.role.RolePage - :rtype: twilio.rest.chat.v2.service.role.RolePage + :param version: Version that contains the resource + :param service_sid: + :param sid: """ - super(RolePage, 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}/Roles/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RoleInstance + Deletes 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: True if delete succeeds, False otherwise """ - return RoleInstance(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 RoleInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RoleContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> RoleInstance: """ - Initialize the RoleContext + Fetch the RoleInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the Role resource to fetch - :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 = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: """ - Fetch the RoleInstance + Asynchronous coroutine to fetch the RoleInstance + :returns: The fetched RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, permission: List[str]) -> RoleInstance: """ - Deletes the RoleInstance + Update the RoleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param permission: + + :returns: The updated RoleInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, permission): + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: """ - Update the RoleInstance + Asynchronous coroutine to update the RoleInstance - :param unicode permission: A permission the role should have + :param permission: :returns: The updated RoleInstance - :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ - data = values.of({'Permission': serialize.map(permission, lambda e: e), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return RoleInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'permissions': payload.get('permissions'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 string that you assigned to describe the resource - :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 of role - :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: An array of the permissions the role has been granted - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Role 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance """ - Fetch the RoleInstance + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) - :returns: The 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: A permission the role should have + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext - :returns: The 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 c453c4f95a..f5f1454c72 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -1,563 +1,804 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the UserList +class UserInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" - :returns: twilio.rest.chat.v2.service.user.UserList - :rtype: twilio.rest.chat.v2.service.user.UserList - """ - super(UserList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Users'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None - def create(self, identity, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + @property + def _proxy(self) -> "UserContext": """ - Create the UserInstance - - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode role_sid: The SID of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the new resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + :returns: UserContext for this 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, }) + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete(self) -> bool: + """ + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - 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) - - def get(self, sid): + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": """ - Constructs a UserContext + Asynchronous coroutine to update the UserInstance - :param sid: The SID of the User resource to fetch + :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.UserContext - :rtype: twilio.rest.chat.v2.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( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def user_bindings(self) -> UserBindingList: """ - Constructs a UserContext - - :param sid: The SID of the User resource to fetch + Access the user_bindings + """ + return self._proxy.user_bindings - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + @property + def user_channels(self) -> UserChannelList: + """ + 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 SID of the Service that the resource is associated with + 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 - - def get_instance(self, payload): - """ - Build an instance of UserInstance + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None - :returns: twilio.rest.chat.v2.service.user.UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance + def delete(self) -> bool: """ - return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the UserInstance - 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 UserContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the UserContext + Asynchronous coroutine that deletes the UserInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the resource from - :param sid: The SID of the User resource to fetch - :returns: twilio.rest.chat.v2.service.user.UserContext - :rtype: twilio.rest.chat.v2.service.user.UserContext + :returns: True if delete succeeds, False otherwise """ - 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 + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> UserInstance: """ Fetch the UserInstance + :returns: The fetched UserInstance - :rtype: twilio.rest.chat.v2.service.user.UserInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> UserInstance: """ - Deletes the UserInstance + Asynchronous coroutine to fetch the UserInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched UserInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, role_sid=values.unset, attributes=values.unset, - friendly_name=values.unset, x_twilio_webhook_enabled=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: """ Update the UserInstance - :param unicode role_sid: The SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :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 - :rtype: twilio.rest.chat.v2.service.user.UserInstance """ - data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, }) - headers = values.of({'X-Twilio-Webhook-Enabled': x_twilio_webhook_enabled, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return UserInstance( self._version, payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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): - """ """ - - class WebhookEnabledType(object): - TRUE = "true" - FALSE = "false" - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'attributes': payload.get('attributes'), - 'friendly_name': payload.get('friendly_name'), - 'role_sid': payload.get('role_sid'), - 'identity': payload.get('identity'), - 'is_online': payload.get('is_online'), - 'is_notifiable': payload.get('is_notifiable'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'joined_channels_count': deserialize.integer(payload.get('joined_channels_count')), - 'links': payload.get('links'), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def attributes(self): - """ - :returns: The JSON string that stores application-specific data - :rtype: unicode - """ - return self._properties['attributes'] +class UserList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the UserList - @property - def role_sid(self): - """ - :returns: The SID of the Role assigned to the user - :rtype: unicode - """ - return self._properties['role_sid'] + :param version: Version that contains the resource + :param service_sid: - @property - def identity(self): - """ - :returns: The string that identifies the resource's User - :rtype: unicode """ - return self._properties['identity'] + super().__init__(version) - @property - def is_online(self): - """ - :returns: Whether the User is actively connected to the Service instance and online - :rtype: bool + # 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: """ - return self._properties['is_online'] + Create the UserInstance - @property - def is_notifiable(self): + :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 """ - :returns: Whether the User has a potentially valid Push Notification registration for the Service instance - :rtype: bool + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance """ - return self._properties['is_notifiable'] - @property - def date_created(self): + 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 number of Channels the User is a Member of - :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 absolute URLs of the Channel and Binding resources related to the user - :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 absolute URL of the User resource - :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"}) - def fetch(self): + 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: """ - Fetch the UserInstance + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately - :returns: The 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" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) - def delete(self): + 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, x_twilio_webhook_enabled=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 SID id of the Role assigned to this user - :param unicode attributes: A valid JSON string that contains application-specific data - :param unicode friendly_name: A string to describe the resource - :param UserInstance.WebhookEnabledType x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The 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, - x_twilio_webhook_enabled=x_twilio_webhook_enabled, - ) + 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 fb5d2913bf..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,450 +1,552 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with - :param user_sid: The SID of the User with the binding + 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 push technology used by the User Binding resources to read - :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']) + :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 push technology used by the User Binding resources to read - :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 push technology used by the User Binding resources to read - :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) + 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 of the User Binding resource to fetch + 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 of the User Binding resource to fetch - :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 SID of the Service that the resource is associated with - :param user_sid: The SID of the User with the binding - :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 SID of the Service to fetch the resource from - :param user_sid: The SID of the User with the binding - :param sid: The SID of the User Binding resource to fetch + 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 the UserBindingInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The fetched UserBindingInstance - :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'endpoint': payload.get('endpoint'), - 'identity': payload.get('identity'), - 'user_sid': payload.get('user_sid'), - 'credential_sid': payload.get('credential_sid'), - 'binding_type': payload.get('binding_type'), - 'message_types': payload.get('message_types'), - 'url': payload.get('url'), - } + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - # Context - self._context = None + """ + super().__init__(version) + + # 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 unique string that identifies the resource - :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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + 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]: """ - 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 unique endpoint identifier for the User Binding - :rtype: unicode - """ - return self._properties['endpoint'] + return self._version.stream_async(page, limits["limit"]) - @property - def identity(self): - """ - :returns: The string that identifies the resource's User - :rtype: unicode + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: """ - 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 SID of the User with the binding - :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 SID of the Credential for the binding - :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 push technology to use for the binding - :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 Programmable Chat message types the binding is subscribed to - :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 absolute URL of the User Binding resource - :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 the UserBindingInstance + Constructs a UserBindingContext - :returns: The 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 5016fa4d55..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,485 +1,666 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 UserChannelList(ListResource): - """ """ +class UserChannelInstance(InstanceResource): - def __init__(self, version, service_sid, user_sid): - """ - Initialize the UserChannelList + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelList - """ - super(UserChannelList, self).__init__(version) + """ + :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") + ) - # 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, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "UserChannelContext": """ - 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. + 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: 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the UserChannelInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 UserChannelInstance 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 UserChannelInstance - :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_channel.UserChannelInstance] + :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) -> "UserChannelInstance": """ - Retrieve a single page of UserChannelInstance records from the API. - Request is executed immediately + Fetch 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 - :returns: Page of UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :returns: The fetched UserChannelInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return UserChannelPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "UserChannelInstance": """ - Retrieve a specific page of UserChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the UserChannelInstance - :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 + :returns: The fetched UserChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return UserChannelPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, 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": """ - Constructs a UserChannelContext + Update the UserChannelInstance - :param channel_sid: The SID of the Channel that has the User Channel to fetch + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: The updated UserChannelInstance """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - def __call__(self, 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": """ - Constructs a UserChannelContext + Asynchronous coroutine to update the UserChannelInstance - :param channel_sid: The SID of the Channel that has the User Channel to fetch + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: The updated UserChannelInstance """ - return UserChannelContext( - self._version, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], - channel_sid=channel_sid, + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, ) - def __repr__(self): + 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 UserChannelPage(Page): - """ """ +class UserChannelContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): """ - Initialize the UserChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param user_sid: The SID of the User the User Channel belongs to + Initialize the UserChannelContext - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param channel_sid: """ - super(UserChannelPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of 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 - """ - return UserChannelInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - user_sid=self._solution['user_sid'], + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) ) - def __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the UserChannelInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class UserChannelContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, user_sid, channel_sid): + async def delete_async(self) -> bool: """ - Initialize the UserChannelContext + Asynchronous coroutine that deletes the UserChannelInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the User Channel resource from - :param user_sid: The SID of the User to fetch the User Channel resource from - :param channel_sid: The SID of the Channel that has the User Channel to fetch - :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :returns: True if delete succeeds, False otherwise """ - super(UserChannelContext, self).__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) + headers = values.of({}) - def fetch(self): + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: """ Fetch the UserChannelInstance + :returns: The fetched UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - def delete(self): + async def fetch_async(self) -> UserChannelInstance: """ - Deletes the UserChannelInstance + Asynchronous coroutine to fetch the UserChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched UserChannelInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: """ Update the UserChannelInstance - :param UserChannelInstance.NotificationLevel notification_level: The push notification level to assign to the User Channel - :param unicode last_consumed_message_index: The index of the last Message that the Member has read within the Channel - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: :returns: The updated UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ - data = values.of({ - 'NotificationLevel': notification_level, - 'LastConsumedMessageIndex': last_consumed_message_index, - 'LastConsumptionTimestamp': serialize.iso8601_datetime(last_consumption_timestamp), - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + 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: """ - Provide a friendly representation + Asynchronous coroutine to update the UserChannelInstance - :returns: Machine friendly representation - :rtype: str + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) -class UserChannelInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class ChannelStatus(object): - JOINED = "joined" - INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + headers["Accept"] = "application/json" - class NotificationLevel(object): - DEFAULT = "default" - MUTED = "muted" + 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 __init__(self, version, payload, service_sid, user_sid, channel_sid=None): + 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) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'channel_sid': payload.get('channel_sid'), - 'user_sid': payload.get('user_sid'), - 'member_sid': payload.get('member_sid'), - 'status': payload.get('status'), - 'last_consumed_message_index': deserialize.integer(payload.get('last_consumed_message_index')), - 'unread_messages_count': deserialize.integer(payload.get('unread_messages_count')), - 'links': payload.get('links'), - 'url': payload.get('url'), - 'notification_level': payload.get('notification_level'), - } - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'user_sid': user_sid, - 'channel_sid': channel_sid or self._properties['channel_sid'], - } +class UserChannelPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ - 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 UserChannelInstance - :returns: UserChannelContext for this UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext + :param payload: Payload response from the API """ - 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 + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['service_sid'] + return "" - @property - def channel_sid(self): - """ - :returns: The SID of the Channel the resource belongs to - :rtype: unicode - """ - return self._properties['channel_sid'] - @property - def user_sid(self): - """ - :returns: The SID of the User the User Channel belongs to - :rtype: unicode +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): """ - return self._properties['user_sid'] + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: - @property - def member_sid(self): """ - :returns: The SID of the User as a Member in the Channel - :rtype: unicode + 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]: """ - return self._properties['member_sid'] + 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 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 of the User on the Channel - :rtype: UserChannelInstance.ChannelStatus + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["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['status'] + 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 last_consumed_message_index(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 index of the last Message in the Channel the Member has read - :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[UserChannelInstance]: """ - return self._properties['last_consumed_message_index'] + 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 unread_messages_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 number of unread Messages in the Channel for the User - :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['unread_messages_count'] + 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 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: Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel - :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, + ) -> UserChannelPage: """ - return self._properties['links'] + Retrieve a single page of UserChannelInstance 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 UserChannelInstance """ - :returns: The absolute URL of the 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 = 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['url'] + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately - @property - def notification_level(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 push notification level of the User for the Channel - :rtype: UserChannelInstance.NotificationLevel + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/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['notification_level'] + Retrieve a specific page of UserChannelInstance 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 UserChannelInstance """ - Fetch the UserChannelInstance + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - :returns: The fetched UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + async def get_page_async(self, target_url: str) -> UserChannelPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of UserChannelInstance """ - Deletes the UserChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, channel_sid: str) -> UserChannelContext: """ - return self._proxy.delete() + Constructs a UserChannelContext - def update(self, notification_level=values.unset, - last_consumed_message_index=values.unset, - last_consumption_timestamp=values.unset): + :param channel_sid: """ - Update the UserChannelInstance + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) - :param UserChannelInstance.NotificationLevel notification_level: The push notification level to assign to the User Channel - :param unicode last_consumed_message_index: The index of the last Message that the Member has read within the Channel - :param datetime last_consumption_timestamp: The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext - :returns: The updated UserChannelInstance - :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance + :param channel_sid: """ - return self._proxy.update( - notification_level=notification_level, - last_consumed_message_index=last_consumed_message_index, - last_consumption_timestamp=last_consumption_timestamp, + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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 bfbad80ce0..6a984f81ca 100644 --- a/twilio/rest/lookups/__init__.py +++ b/twilio/rest/lookups/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -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 b5a74c806c..72204da366 100644 --- a/twilio/rest/lookups/v1/__init__.py +++ b/twilio/rest/lookups/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 4709062783..304b89ab15 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -1,288 +1,272 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 to fetch in E.164 format + :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 to fetch in E.164 format + :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 + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance + 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 PhoneNumberInstance(self._version, payload, ) + Fetch the PhoneNumberInstance - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: The fetched PhoneNumberInstance """ - return '' + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) -class PhoneNumberContext(InstanceContext): - """ """ + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - def __init__(self, version, phone_number): - """ - Initialize the PhoneNumberContext + headers = values.of({}) - :param Version version: Version that contains the resource - :param phone_number: The phone number to fetch in E.164 format + headers["Accept"] = "application/json" - :returns: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext - """ - super(PhoneNumberContext, self).__init__(version) + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - # Path Solution - self._solution = {'phone_number': phone_number, } - self._uri = '/PhoneNumbers/{phone_number}'.format(**self._solution) + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) - def fetch(self, country_code=values.unset, type=values.unset, - add_ons=values.unset, add_ons_data=values.unset): + 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: """ - Fetch the PhoneNumberInstance + Asynchronous coroutine to fetch the PhoneNumberInstance - :param unicode country_code: The ISO country code of the phone number - :param unicode type: The type of information to return - :param unicode add_ons: The unique_name of an Add-on you would like to invoke - :param dict add_ons_data: Data specific to the add-on you would like to invoke + :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 - :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberInstance """ - data = values.of({ - 'CountryCode': country_code, - 'Type': serialize.map(type, lambda e: e), - 'AddOns': serialize.map(add_ons, lambda e: e), - }) - data.update(serialize.prefixed_collapsible_map(add_ons_data, 'AddOns')) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - - return PhoneNumberInstance(self._version, payload, phone_number=self._solution['phone_number'], ) - - 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) + 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.get('caller_name'), - 'country_code': payload.get('country_code'), - 'phone_number': payload.get('phone_number'), - 'national_format': payload.get('national_format'), - 'carrier': payload.get('carrier'), - 'add_ons': payload.get('add_ons'), - 'url': payload.get('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 name of the phone number's owner - :rtype: dict - """ - return self._properties['caller_name'] - @property - def country_code(self): - """ - :returns: The ISO country code for the phone number - :rtype: unicode - """ - return self._properties['country_code'] +class PhoneNumberList(ListResource): - @property - def phone_number(self): - """ - :returns: The phone number in E.164 format - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['phone_number'] + Initialize the PhoneNumberList - @property - def national_format(self): - """ - :returns: The phone number, in national format - :rtype: unicode - """ - return self._properties['national_format'] + :param version: Version that contains the resource - @property - def carrier(self): - """ - :returns: The telecom company that provides the phone number - :rtype: dict """ - return self._properties['carrier'] + super().__init__(version) - @property - def add_ons(self): - """ - :returns: A JSON string with the results of the Add-ons you specified - :rtype: dict + def get(self, phone_number: str) -> PhoneNumberContext: """ - return self._properties['add_ons'] + Constructs a PhoneNumberContext - @property - def url(self): - """ - :returns: The absolute URL of the resource - :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 the PhoneNumberInstance - - :param unicode country_code: The ISO country code of the phone number - :param unicode type: The type of information to return - :param unicode add_ons: The unique_name of an Add-on you would like to invoke - :param dict add_ons_data: Data specific to the add-on you would like to invoke + Constructs a PhoneNumberContext - :returns: The 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 f764e1dce4..4e62832592 100644 --- a/twilio/rest/messaging/__init__.py +++ b/twilio/rest/messaging/__init__.py @@ -1,53 +1,99 @@ -# coding=utf-8 -r""" -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 923e696066..6bd630fbd8 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -1,42 +1,151 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 5aa89b7b1e..06a53c9a20 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -1,698 +1,1115 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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. """ +class ServiceInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the ServiceList + class ScanMessageContent(object): + INHERIT = "inherit" + ENABLE = "enable" + DISABLE = "disable" - :param Version version: Version that contains the resource + """ + :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" + ) - :returns: twilio.rest.messaging.v1.service.ServiceList - :rtype: twilio.rest.messaging.v1.service.ServiceList + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": """ - super(ServiceList, 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 = '/Services'.format(**self._solution) + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - 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): + def delete(self) -> bool: """ - Create the ServiceInstance + Deletes the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode 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 - :param unicode inbound_method: The HTTP method we should use to call inbound_request_url - :param unicode 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 - :param unicode fallback_method: The HTTP method we should use to call fallback_url - :param unicode status_callback: The URL we should call to pass status updates about message delivery - :param bool sticky_sender: Whether to enable Sticky Sender on the Service instance - :param bool mms_converter: Whether to enable the MMS Converter for messages sent through the Service instance - :param bool smart_encoding: Whether to enable Encoding for messages sent through the Service instance - :param ServiceInstance.ScanMessageContent scan_message_content: Reserved - :param bool fallback_to_long_code: Whether to enable Fallback to Long Code for messages sent through the Service instance - :param bool area_code_geomatch: Whether to enable Area Code Geomatch on the Service Instance - :param unicode validity_period: How long, in seconds, messages sent from the Service are valid - :param bool synchronous_validation: Reserved - :returns: The 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - 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.messaging.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']) + :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.messaging.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.messaging.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return ServicePage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated ServiceInstance """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ServicePage(self._version, response, self._solution) + @property + def alpha_senders(self) -> AlphaSenderList: + """ + Access the alpha_senders + """ + return self._proxy.alpha_senders - def get(self, sid): + @property + def channel_senders(self) -> ChannelSenderList: """ - Constructs a ServiceContext + Access the channel_senders + """ + return self._proxy.channel_senders - :param sid: The SID that identifies the resource to fetch + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.phone_numbers - def __call__(self, sid): + @property + def short_codes(self) -> ShortCodeList: """ - Constructs a ServiceContext + Access the short_codes + """ + return self._proxy.short_codes - :param sid: The SID that identifies the resource to fetch + @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 that identifies the resource to fetch - :returns: twilio.rest.messaging.v1.service.ServiceContext - :rtype: twilio.rest.messaging.v1.service.ServiceContext + :returns: True if delete succeeds, False otherwise """ - 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): - """ - Update the ServiceInstance + headers = values.of({}) - :param unicode friendly_name: A string to describe the resource - :param unicode 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 - :param unicode inbound_method: The HTTP method we should use to call inbound_request_url - :param unicode 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 - :param unicode fallback_method: The HTTP method we should use to call fallback_url - :param unicode status_callback: The URL we should call to pass status updates about message delivery - :param bool sticky_sender: Whether to enable Sticky Sender on the Service instance - :param bool mms_converter: Whether to enable the MMS Converter for messages sent through the Service instance - :param bool smart_encoding: Whether to enable Encoding for messages sent through the Service instance - :param ServiceInstance.ScanMessageContent scan_message_content: Reserved - :param bool fallback_to_long_code: Whether to enable Fallback to Long Code for messages sent through the Service instance - :param bool area_code_geomatch: Whether to enable Area Code Geomatch on the Service Instance - :param unicode validity_period: How long, in seconds, messages sent from the Service are valid - :param bool synchronous_validation: Reserved + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - :returns: The 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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) - - def fetch(self): + def fetch(self) -> ServiceInstance: """ Fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the ServiceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - @property - def phone_numbers(self): - """ - Access the phone_numbers + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberList + async def fetch_async(self) -> ServiceInstance: """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList(self._version, service_sid=self._solution['sid'], ) - return self._phone_numbers + Asynchronous coroutine to fetch the ServiceInstance - @property - def short_codes(self): - """ - Access the short_codes - :returns: twilio.rest.messaging.v1.service.short_code.ShortCodeList - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeList + :returns: The fetched ServiceInstance """ - if self._short_codes is None: - self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], ) - return self._short_codes - @property - def alpha_senders(self): - """ - Access the alpha_senders + headers = values.of({}) - :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 + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __repr__(self): + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ - Provide a friendly representation + Update the ServiceInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'inbound_request_url': payload.get('inbound_request_url'), - 'inbound_method': payload.get('inbound_method'), - 'fallback_url': payload.get('fallback_url'), - 'fallback_method': payload.get('fallback_method'), - 'status_callback': payload.get('status_callback'), - 'sticky_sender': payload.get('sticky_sender'), - 'mms_converter': payload.get('mms_converter'), - 'smart_encoding': payload.get('smart_encoding'), - 'scan_message_content': payload.get('scan_message_content'), - 'fallback_to_long_code': payload.get('fallback_to_long_code'), - 'area_code_geomatch': payload.get('area_code_geomatch'), - 'synchronous_validation': payload.get('synchronous_validation'), - 'validity_period': deserialize.integer(payload.get('validity_period')), - 'url': payload.get('url'), - 'links': payload.get('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. - @property - def _proxy(self): + :returns: The updated ServiceInstance """ - 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.messaging.v1.service.ServiceContext - """ - if self._context is None: - self._context = ServiceContext(self._version, sid=self._solution['sid'], ) - return self._context + 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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def date_updated(self): + def alpha_senders(self) -> AlphaSenderList: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Access the alpha_senders """ - return self._properties['date_updated'] + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._alpha_senders @property - def inbound_request_url(self): + def channel_senders(self) -> ChannelSenderList: """ - :returns: The URL we call using inbound_method when a message is received by any phone number or short code in the Service - :rtype: unicode + Access the channel_senders """ - return self._properties['inbound_request_url'] + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + return self._channel_senders @property - def inbound_method(self): + def destination_alpha_senders(self) -> DestinationAlphaSenderList: """ - :returns: The HTTP method we use to call inbound_request_url - :rtype: unicode + Access the destination_alpha_senders """ - return self._properties['inbound_method'] + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders @property - def fallback_url(self): + def phone_numbers(self) -> PhoneNumberList: """ - :returns: The URL that we call using fallback_method if an error occurs while retrieving or executing the TwiML from the Inbound Request URL - :rtype: unicode + Access the phone_numbers """ - return self._properties['fallback_url'] + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers @property - def fallback_method(self): + def short_codes(self) -> ShortCodeList: """ - :returns: The HTTP method we use to call fallback_url - :rtype: unicode + Access the short_codes """ - return self._properties['fallback_method'] + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes @property - def status_callback(self): + def us_app_to_person(self) -> UsAppToPersonList: """ - :returns: The URL we call to pass status updates about message delivery - :rtype: unicode + Access the us_app_to_person """ - return self._properties['status_callback'] + 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 sticky_sender(self): + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: """ - :returns: Whether to enable Sticky Sender on the Service instance - :rtype: bool + Access the us_app_to_person_usecases """ - return self._properties['sticky_sender'] + 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 mms_converter(self): - """ - :returns: Whether to enable the MMS Converter for messages sent through the Service instance - :rtype: bool + def __repr__(self) -> str: """ - return self._properties['mms_converter'] + Provide a friendly representation - @property - def smart_encoding(self): + :returns: Machine friendly representation """ - :returns: Whether to enable Encoding for messages sent through the Service instance - :rtype: bool + 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: """ - return self._properties['smart_encoding'] + Build an instance of ServiceInstance - @property - def scan_message_content(self): + :param payload: Payload response from the API """ - :returns: Reserved - :rtype: ServiceInstance.ScanMessageContent + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['scan_message_content'] + Provide a friendly representation - @property - def fallback_to_long_code(self): + :returns: Machine friendly representation """ - :returns: Whether to enable Fallback to Long Code for messages sent through the Service instance - :rtype: bool + return "" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['fallback_to_long_code'] + Initialize the ServiceList - @property - def area_code_geomatch(self): + :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: """ - :returns: Whether to enable Area Code Geomatch on the Service Instance - :rtype: bool + 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 """ - return self._properties['area_code_geomatch'] - @property - def synchronous_validation(self): + 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 """ - :returns: Reserved - :rtype: bool + + 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: How long, in seconds, messages sent from the Service are valid - :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 absolute URL of the Service 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: The absolute URLs of related resources - :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: A string to describe the resource - :param unicode 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 - :param unicode inbound_method: The HTTP method we should use to call inbound_request_url - :param unicode 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 - :param unicode fallback_method: The HTTP method we should use to call fallback_url - :param unicode status_callback: The URL we should call to pass status updates about message delivery - :param bool sticky_sender: Whether to enable Sticky Sender on the Service instance - :param bool mms_converter: Whether to enable the MMS Converter for messages sent through the Service instance - :param bool smart_encoding: Whether to enable Encoding for messages sent through the Service instance - :param ServiceInstance.ScanMessageContent scan_message_content: Reserved - :param bool fallback_to_long_code: Whether to enable Fallback to Long Code for messages sent through the Service instance - :param bool area_code_geomatch: Whether to enable Area Code Geomatch on the Service Instance - :param unicode validity_period: How long, in seconds, messages sent from the Service are valid - :param bool synchronous_validation: Reserved + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The updated ServiceInstance - :rtype: twilio.rest.messaging.v1.service.ServiceInstance + :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, + } ) - def fetch(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: """ - Fetch the ServiceInstance + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: The fetched 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.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 9df195041d..2ba4c2a45c 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -1,395 +1,542 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + :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 the AlphaSenderInstance - - :param unicode alpha_sender: The Alphanumeric Sender ID string + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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. - - :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.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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AlphaSenderContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a AlphaSenderContext + Asynchronous coroutine that deletes the AlphaSenderInstance - :param sid: The SID that identifies the resource to fetch - :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 that identifies the resource to fetch - :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 + ) + + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderPage + :returns: Machine friendly representation """ - super(AlphaSenderPage, 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 AlphaSenderPage(Page): + + 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 SID of the Messaging Service to fetch the resource from - :param sid: The SID that identifies the resource to fetch + :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 the AlphaSenderInstance + Create the AlphaSenderInstance - :returns: The fetched AlphaSenderInstance - :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'alpha_sender': payload.get('alpha_sender'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 Alphanumeric Sender ID string - :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: An array of values that describe whether the number can receive calls or messages - :rtype: unicode + 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 absolute URL of the AlphaSender resource - :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 the AlphaSenderInstance + Constructs a AlphaSenderContext - :returns: The 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 1313cf5b83..11b806583e 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -1,404 +1,544 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + :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 the PhoneNumberInstance - - :param unicode phone_number_sid: The SID of the Phone Number being added to the Service + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the PhoneNumberContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get(self, sid): + async def delete_async(self) -> bool: """ - Constructs a PhoneNumberContext + Asynchronous coroutine that deletes the PhoneNumberInstance - :param sid: The SID that identifies the resource to fetch - :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 that identifies the resource to fetch - :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 + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberPage + :returns: Machine friendly representation """ - super(PhoneNumberPage, 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 PhoneNumberPage(Page): + + 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 SID of the Service to fetch the resource from - :param sid: The SID that identifies the resource to fetch + :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(method='DELETE', uri=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 the PhoneNumberInstance - :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) return PhoneNumberInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - 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 - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :param phone_number_sid: The SID of the Phone Number being added to the Service. + :returns: The created PhoneNumberInstance + """ -class PhoneNumberInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the PhoneNumberInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - :rtype: twilio.rest.messaging.v1.service.phone_number.PhoneNumberInstance - """ - super(PhoneNumberInstance, self).__init__(version) + headers["Accept"] = "application/json" - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'phone_number': payload.get('phone_number'), - 'country_code': payload.get('country_code'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 in E.164 format - :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 2-character ISO Country Code of the number - :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: An array of values that describe whether the number can receive calls or messages - :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 absolute URL of the PhoneNumber resource - :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 the PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: The 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 9762fd248a..172c78dbb9 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -1,404 +1,542 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + :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 the ShortCodeInstance - - :param unicode short_code_sid: The SID of the ShortCode being added to the Service + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the ShortCodeContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 that identifies the resource to fetch - :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 that identifies the resource to fetch - :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 SID of the Service that the resource is associated with + 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 - # 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 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 SID of the Service to fetch the resource from - :param sid: The SID that identifies the resource to fetch + :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(method='DELETE', uri=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 the ShortCodeInstance - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodeInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'short_code': payload.get('short_code'), - 'country_code': payload.get('country_code'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Service that the resource is associated with - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 E.164 format of 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 2-character ISO Country Code of the number - :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: An array of values that describe whether the number can receive calls or messages - :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['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 absolute URL of the ShortCode resource - :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 the ShortCodeInstance + Constructs a ShortCodeContext - :returns: The 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 3c4ba1e5c8..a39a5b248a 100644 --- a/twilio/rest/monitor/__init__.py +++ b/twilio/rest/monitor/__init__.py @@ -1,60 +1,25 @@ -# coding=utf-8 -r""" -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 b0a876cdce..e892612b3b 100644 --- a/twilio/rest/monitor/v1/__init__.py +++ b/twilio/rest/monitor/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 6a87c647ae..829e633643 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -1,476 +1,501 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: Only show alerts for this log-level - :param datetime start_date: Only include alerts that occurred on or after this date and time - :param datetime end_date: Only include alerts that occurred on or before this date and 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) - :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']) - 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: Only show alerts for this log-level - :param datetime start_date: Only include alerts that occurred on or after this date and time - :param datetime end_date: Only include alerts that occurred on or before this date and 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) - - :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: Only show alerts for this log-level - :param datetime start_date: Only include alerts that occurred on or after this date and time - :param datetime end_date: Only include alerts that occurred on or before this date and 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 - :returns: Page of AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertPage +class AlertContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - 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, - }) + Initialize the AlertContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 that identifies the resource to fetch + 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 that identifies the resource to fetch - :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 that identifies the resource to fetch + :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) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Alerts/{sid}'.format(**self._solution) + super().__init__(version) - def fetch(self): - """ - Fetch the AlertInstance + self._uri = "/Alerts" - :returns: The fetched AlertInstance - :rtype: twilio.rest.monitor.v1.alert.AlertInstance + 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]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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. - return AlertInstance(self._version, payload, sid=self._solution['sid'], ) + :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) - 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( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) - :returns: Machine friendly representation - :rtype: str + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlertInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + Asynchronously streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) -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.get('account_sid'), - 'alert_text': payload.get('alert_text'), - 'api_version': payload.get('api_version'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_generated': deserialize.iso8601_datetime(payload.get('date_generated')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'error_code': payload.get('error_code'), - 'log_level': payload.get('log_level'), - 'more_info': payload.get('more_info'), - 'request_method': payload.get('request_method'), - 'request_url': payload.get('request_url'), - 'request_variables': payload.get('request_variables'), - 'resource_sid': payload.get('resource_sid'), - 'response_body': payload.get('response_body'), - 'response_headers': payload.get('response_headers'), - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'request_headers': payload.get('request_headers'), - 'service_sid': payload.get('service_sid'), - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) - # 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 SID of the Account that created the resource - :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): - """ - :returns: The text of the alert - :rtype: unicode + :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: """ - 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 used when the alert was generated - :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 ISO 8601 date and time in GMT when the resource was 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 and time when the alert was generated specified in ISO 8601 format - :rtype: datetime - """ - return self._properties['date_generated'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + headers["Accept"] = "application/json" - @property - def error_code(self): - """ - :returns: The error code for the condition that generated the alert - :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 URL of the page in our Error Dictionary with more information about the error condition - :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 method used by the request that generated the alert - :rtype: unicode - """ - return self._properties['request_method'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def request_url(self): - """ - :returns: The URL of the request that generated the alert - :rtype: unicode - """ - return self._properties['request_url'] + headers["Accept"] = "application/json" - @property - def request_variables(self): - """ - :returns: The variables passed in the request that generated the alert - :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): - """ - :returns: The SID of the resource for which the alert was generated - :rtype: unicode + def get_page(self, target_url: str) -> AlertPage: """ - 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 of the request that generated the alert - :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 of the request that generated the alert - :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): + async def get_page_async(self, target_url: str) -> AlertPage: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 absolute URL of the Alert resource - :rtype: unicode - """ - return self._properties['url'] + :param target_url: API-generated URL for the requested results page - @property - def request_headers(self): - """ - :returns: The request headers of the request that generated the alert - :rtype: unicode + :returns: Page of AlertInstance """ - return self._properties['request_headers'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlertPage(self._version, response) - @property - def service_sid(self): + def get(self, sid: str) -> AlertContext: """ - :returns: The SID of the service or resource that generated the alert - :rtype: unicode + Constructs a AlertContext + + :param sid: The SID of the Alert resource to fetch. """ - return self._properties['service_sid'] + return AlertContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> AlertContext: """ - Fetch the AlertInstance + Constructs a AlertContext - :returns: The 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 __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 c0697343ce..61450c872c 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -1,455 +1,541 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: Only include events initiated by this Actor - :param unicode event_type: Only include events of this Event Type - :param unicode resource_sid: Only include events that refer to this resource - :param unicode source_ip_address: Only include events that originated from this IP address - :param datetime start_date: Only include events that occurred on or after this date - :param datetime end_date: Only include events that occurred on or before this 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) + return self._proxy.fetch() - 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'], - ) + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance - return self._version.stream(page, limits['limit']) - 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): + :returns: The fetched 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 unicode actor_sid: Only include events initiated by this Actor - :param unicode event_type: Only include events of this Event Type - :param unicode resource_sid: Only include events that refer to this resource - :param unicode source_ip_address: Only include events that originated from this IP address - :param datetime start_date: Only include events that occurred on or after this date - :param datetime end_date: Only include events that occurred on or before this 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) + return await self._proxy.fetch_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.monitor.v1.event.EventInstance] + def __repr__(self) -> str: """ - 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, - )) + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Retrieve a single page of EventInstance 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 actor_sid: Only include events initiated by this Actor - :param unicode event_type: Only include events of this Event Type - :param unicode resource_sid: Only include events that refer to this resource - :param unicode source_ip_address: Only include events that originated from this IP address - :param datetime start_date: Only include events that occurred on or after this date - :param datetime end_date: Only include events that occurred on or before this 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 EventInstance - :rtype: twilio.rest.monitor.v1.event.EventPage +class EventContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - 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, - }) + Initialize the EventContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) - return EventPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Events/{sid}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> EventInstance: """ - Retrieve a specific page of EventInstance records from the API. - Request is executed immediately + Fetch the EventInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of EventInstance - :rtype: twilio.rest.monitor.v1.event.EventPage + :returns: The fetched EventInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return EventPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a EventContext + headers["Accept"] = "application/json" - :param sid: The SID that identifies the resource to fetch + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext - """ - return EventContext(self._version, sid=sid, ) + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> EventInstance: """ - Constructs a EventContext + Asynchronous coroutine to fetch the EventInstance - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.monitor.v1.event.EventContext - :rtype: twilio.rest.monitor.v1.event.EventContext + :returns: The fetched EventInstance """ - return EventContext(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 EventPage(Page): - """ """ + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the EventPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.monitor.v1.event.EventPage - :rtype: twilio.rest.monitor.v1.event.EventPage + :returns: Machine friendly representation """ - super(EventPage, 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 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 that identifies the resource to fetch + :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 the 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: The fetched EventInstance - :rtype: twilio.rest.monitor.v1.event.EventInstance + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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.get('account_sid'), - 'actor_sid': payload.get('actor_sid'), - 'actor_type': payload.get('actor_type'), - 'description': payload.get('description'), - 'event_data': payload.get('event_data'), - 'event_date': deserialize.iso8601_datetime(payload.get('event_date')), - 'event_type': payload.get('event_type'), - 'resource_sid': payload.get('resource_sid'), - 'resource_type': payload.get('resource_type'), - 'sid': payload.get('sid'), - 'source': payload.get('source'), - 'source_ip_address': payload.get('source_ip_address'), - 'url': payload.get('url'), - 'links': payload.get('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 SID of the Account that created the resource - :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 SID of the actor that caused the event, if available - :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 type of actor that caused the event - :rtype: unicode - """ - return self._properties['actor_type'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def description(self): - """ - :returns: A description of the event - :rtype: unicode - """ - return self._properties['description'] + headers["Accept"] = "application/json" - @property - def event_data(self): - """ - :returns: A JSON string that represents an object with additional data about the event - :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 ISO 8601 date and time in GMT when the event was recorded - :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's 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 SID of the resource that was affected - :rtype: unicode - """ - return self._properties['resource_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def resource_type(self): - """ - :returns: The type of resource that was affected - :rtype: unicode - """ - return self._properties['resource_type'] + headers["Accept"] = "application/json" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :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): - """ - :returns: The originating system or interface that caused the event - :rtype: unicode + def get_page(self, target_url: str) -> EventPage: """ - 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 IP address of the source - :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 absolute URL of the resource that was affected - :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 absolute URLs of related resources - :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 the EventInstance + Constructs a EventContext - :returns: The 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 888e70e4b3..61f8fafb6b 100644 --- a/twilio/rest/notify/__init__.py +++ b/twilio/rest/notify/__init__.py @@ -1,60 +1,25 @@ -# coding=utf-8 -r""" -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 ee3a97ab0a..90cab95028 100644 --- a/twilio/rest/notify/v1/__init__.py +++ b/twilio/rest/notify/v1/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 9edd701442..9ca59927cb 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -1,458 +1,711 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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. """ +class CredentialInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the CredentialList + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None - :returns: twilio.rest.notify.v1.credential.CredentialList - :rtype: twilio.rest.notify.v1.credential.CredentialList + @property + def _proxy(self) -> "CredentialContext": """ - super(CredentialList, 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 = '/Credentials'.format(**self._solution) + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def delete(self) -> bool: """ - 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. + Deletes the CredentialInstance - :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.credential.CredentialInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.delete() - page = self.page(page_size=limits['page_size'], ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 await self._proxy.delete_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) + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.notify.v1.credential.CredentialInstance] + + :returns: The fetched CredentialInstance """ - 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) -> "CredentialInstance": """ - Retrieve a single page of CredentialInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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: The fetched CredentialInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return CredentialPage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated CredentialInstance """ - Retrieve a specific page of CredentialInstance records from the API. - Request is executed immediately + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :returns: The updated CredentialInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Create the CredentialInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param CredentialInstance.PushService type: The Credential type - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL-encoded representation of the certificate - :param unicode private_key: [APN only] URL-encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging - :param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging - :returns: The created CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'Type': type, - 'FriendlyName': friendly_name, - 'Certificate': certificate, - 'PrivateKey': private_key, - 'Sandbox': sandbox, - 'ApiKey': api_key, - 'Secret': secret, - }) + Initialize the CredentialContext - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) - return CredentialInstance(self._version, payload, ) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) - def get(self, sid): + def delete(self) -> bool: """ - Constructs a CredentialContext + Deletes the CredentialInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + :returns: True if delete succeeds, False otherwise """ - return CredentialContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a CredentialContext + headers = values.of({}) - :param sid: The unique string that identifies the resource + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + async def delete_async(self) -> bool: """ - return CredentialContext(self._version, sid=sid, ) + Asynchronous coroutine that deletes the CredentialInstance - 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 CredentialPage(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) -> CredentialInstance: """ - Initialize the CredentialPage + Fetch the CredentialInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.notify.v1.credential.CredentialPage - :rtype: twilio.rest.notify.v1.credential.CredentialPage + :returns: The fetched CredentialInstance """ - super(CredentialPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of CredentialInstance + 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.notify.v1.credential.CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance - """ - return CredentialInstance(self._version, payload, ) + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> CredentialInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the CredentialInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CredentialInstance """ - return '' + headers = values.of({}) -class CredentialContext(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, sid): - """ - Initialize the CredentialContext + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.notify.v1.credential.CredentialContext - :rtype: twilio.rest.notify.v1.credential.CredentialContext + 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: """ - super(CredentialContext, self).__init__(version) + Update the CredentialInstance - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Credentials/{sid}'.format(**self._solution) + :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. - def fetch(self): + :returns: The updated CredentialInstance """ - Fetch the CredentialInstance - :returns: The fetched CredentialInstance - :rtype: twilio.rest.notify.v1.credential.CredentialInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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: """ - Update the CredentialInstance + Asynchronous coroutine to update the CredentialInstance - :param unicode friendly_name: A string to describe the resource - :param unicode certificate: [APN only] The URL-encoded representation of the certificate - :param unicode private_key: [APN only] URL-encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging - :param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CredentialInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the CredentialInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'sandbox': payload.get('sandbox'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: """ - return self._properties['sid'] + Create the CredentialInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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 """ - 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 = 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 string that you assigned to describe the resource - :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 Credential type, one of `gcm`, `fcm`, or `apn` - :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: [APN only] Whether to send the credential to sandbox APNs - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the Credential 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 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 the CredentialInstance + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) - :returns: The 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: A string to describe the resource - :param unicode certificate: [APN only] The URL-encoded representation of the certificate - :param unicode private_key: [APN only] URL-encoded representation of the private key - :param bool sandbox: [APN only] Whether to send the credential to sandbox APNs - :param unicode api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging - :param unicode secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext - :returns: The 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 586c12b2af..e097e69a67 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -1,689 +1,948 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 -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 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" + ) - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - :returns: twilio.rest.notify.v1.service.ServiceList - :rtype: twilio.rest.notify.v1.service.ServiceList + @property + def _proxy(self) -> "ServiceContext": """ - super(ServiceList, 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 = '/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, - delivery_callback_url=values.unset, - delivery_callback_enabled=values.unset): + :returns: ServiceContext for this ServiceInstance """ - Create the ServiceInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode apn_credential_sid: The SID of the Credential to use for APN Bindings - :param unicode gcm_credential_sid: The SID of the Credential to use for GCM Bindings - :param unicode messaging_service_sid: The SID of the Messaging Service to use for SMS Bindings - :param unicode facebook_messenger_page_id: Deprecated - :param unicode default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications - :param unicode default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications - :param unicode fcm_credential_sid: The SID of the Credential to use for FCM Bindings - :param unicode default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications - :param bool log_enabled: Whether to log notifications - :param unicode alexa_skill_id: Deprecated - :param unicode default_alexa_notification_protocol_version: Deprecated - :param unicode delivery_callback_url: Webhook URL - :param bool delivery_callback_enabled: Enable delivery callbacks + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The 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, - 'DeliveryCallbackUrl': delivery_callback_url, - 'DeliveryCallbackEnabled': delivery_callback_enabled, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, ) - - def stream(self, friendly_name=values.unset, limit=None, page_size=None): + def delete(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. + Deletes the ServiceInstance - :param unicode friendly_name: The string that identifies the Service resources to read - :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.ServiceInstance] + :returns: True if delete succeeds, False otherwise """ - 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']) + 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 string that identifies the Service resources to read - :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 string that identifies the Service resources to read - :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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() + + 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 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 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: Page of ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServicePage + :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 - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + 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, + ) - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + @property + def bindings(self) -> BindingList: """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): + Access the bindings """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + return self._proxy.bindings - :returns: twilio.rest.notify.v1.service.ServiceContext - :rtype: twilio.rest.notify.v1.service.ServiceContext + @property + def notifications(self) -> NotificationList: + """ + 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) + + self._bindings: Optional[BindingList] = None + self._notifications: Optional[NotificationList] = 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.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 unique string that identifies the resource - :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 + 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(method='DELETE', uri=self._uri, ) + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ServiceInstance: """ - Fetch the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" - 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, - delivery_callback_url=values.unset, - delivery_callback_enabled=values.unset): + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode friendly_name: A string to describe the resource - :param unicode apn_credential_sid: The SID of the Credential to use for APN Bindings - :param unicode gcm_credential_sid: The SID of the Credential to use for GCM Bindings - :param unicode messaging_service_sid: The SID of the Messaging Service to use for SMS Bindings - :param unicode facebook_messenger_page_id: Deprecated - :param unicode default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications - :param unicode default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications - :param unicode fcm_credential_sid: The SID of the Credential to use for FCM Bindings - :param unicode default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications - :param bool log_enabled: Whether to log notifications - :param unicode alexa_skill_id: Deprecated - :param unicode default_alexa_notification_protocol_version: Deprecated - :param unicode delivery_callback_url: Webhook URL - :param bool delivery_callback_enabled: Enable delivery callbacks + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false :returns: The updated ServiceInstance - :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, - 'DeliveryCallbackUrl': delivery_callback_url, - 'DeliveryCallbackEnabled': delivery_callback_enabled, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def bindings(self): + 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 - 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.notify.v1.service.ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'apn_credential_sid': payload.get('apn_credential_sid'), - 'gcm_credential_sid': payload.get('gcm_credential_sid'), - 'fcm_credential_sid': payload.get('fcm_credential_sid'), - 'messaging_service_sid': payload.get('messaging_service_sid'), - 'facebook_messenger_page_id': payload.get('facebook_messenger_page_id'), - 'default_apn_notification_protocol_version': payload.get('default_apn_notification_protocol_version'), - 'default_gcm_notification_protocol_version': payload.get('default_gcm_notification_protocol_version'), - 'default_fcm_notification_protocol_version': payload.get('default_fcm_notification_protocol_version'), - 'log_enabled': payload.get('log_enabled'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'alexa_skill_id': payload.get('alexa_skill_id'), - 'default_alexa_notification_protocol_version': payload.get('default_alexa_notification_protocol_version'), - 'delivery_callback_url': payload.get('delivery_callback_url'), - 'delivery_callback_enabled': payload.get('delivery_callback_enabled'), - } - - # 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.notify.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 unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class ServiceList(ListResource): - @property - def date_updated(self): + def __init__(self, version: Version): """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the ServiceList - @property - def apn_credential_sid(self): - """ - :returns: The SID of the Credential to use for APN Bindings - :rtype: unicode - """ - return self._properties['apn_credential_sid'] + :param version: Version that contains the resource - @property - def gcm_credential_sid(self): - """ - :returns: The SID of the Credential to use for GCM Bindings - :rtype: unicode """ - return self._properties['gcm_credential_sid'] + super().__init__(version) - @property - def fcm_credential_sid(self): - """ - :returns: The SID of the Credential to use for FCM Bindings - :rtype: unicode - """ - return self._properties['fcm_credential_sid'] + self._uri = "/Services" - @property - def messaging_service_sid(self): - """ - :returns: The SID of the Messaging Service to use for SMS Bindings - :rtype: unicode + 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: """ - return self._properties['messaging_service_sid'] + Create the ServiceInstance - @property - def facebook_messenger_page_id(self): - """ - :returns: Deprecated - :rtype: unicode - """ - return self._properties['facebook_messenger_page_id'] + :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 - @property - def default_apn_notification_protocol_version(self): - """ - :returns: The protocol version to use for sending APNS notifications - :rtype: unicode + :returns: The created ServiceInstance """ - return self._properties['default_apn_notification_protocol_version'] - @property - def default_gcm_notification_protocol_version(self): - """ - :returns: The protocol version to use for sending GCM notifications - :rtype: unicode - """ - return self._properties['default_gcm_notification_protocol_version'] + 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 default_fcm_notification_protocol_version(self): - """ - :returns: The protocol version to use for sending FCM notifications - :rtype: unicode - """ - return self._properties['default_fcm_notification_protocol_version'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def log_enabled(self): - """ - :returns: Whether to log notifications - :rtype: bool - """ - return self._properties['log_enabled'] + headers["Accept"] = "application/json" - @property - def url(self): - """ - :returns: The absolute URL of the Service resource - :rtype: unicode - """ - return self._properties['url'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def links(self): - """ - :returns: The URLs of the resources related to the service - :rtype: unicode + 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 """ - return self._properties['links'] - @property - def alexa_skill_id(self): + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: """ - :returns: Deprecated - :rtype: unicode + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['alexa_skill_id'] + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) - @property - def default_alexa_notification_protocol_version(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[ServiceInstance]: """ - :returns: Deprecated - :rtype: unicode + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['default_alexa_notification_protocol_version'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) - @property - def delivery_callback_url(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[ServiceInstance]: """ - :returns: Webhook URL - :rtype: unicode + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - return self._properties['delivery_callback_url'] + 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. - @property - def delivery_callback_enabled(self): + :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: """ - :returns: Enable delivery callbacks - :rtype: bool + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance """ - return self._properties['delivery_callback_enabled'] + 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 delete(self): + 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: """ - 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 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.delete() + 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 fetch(self): + 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: """ - Fetch the ServiceInstance + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: The fetched ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - 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, - delivery_callback_url=values.unset, - delivery_callback_enabled=values.unset): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Update the ServiceInstance + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource - :param unicode apn_credential_sid: The SID of the Credential to use for APN Bindings - :param unicode gcm_credential_sid: The SID of the Credential to use for GCM Bindings - :param unicode messaging_service_sid: The SID of the Messaging Service to use for SMS Bindings - :param unicode facebook_messenger_page_id: Deprecated - :param unicode default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications - :param unicode default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications - :param unicode fcm_credential_sid: The SID of the Credential to use for FCM Bindings - :param unicode default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications - :param bool log_enabled: Whether to log notifications - :param unicode alexa_skill_id: Deprecated - :param unicode default_alexa_notification_protocol_version: Deprecated - :param unicode delivery_callback_url: Webhook URL - :param bool delivery_callback_enabled: Enable delivery callbacks + :param target_url: API-generated URL for the requested results page - :returns: The updated ServiceInstance - :rtype: twilio.rest.notify.v1.service.ServiceInstance + :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, - delivery_callback_url=delivery_callback_url, - delivery_callback_enabled=delivery_callback_enabled, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def bindings(self): + def get(self, sid: str) -> ServiceContext: """ - Access the bindings + Constructs a ServiceContext - :returns: twilio.rest.notify.v1.service.binding.BindingList - :rtype: twilio.rest.notify.v1.service.binding.BindingList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.bindings + return ServiceContext(self._version, sid=sid) - @property - def notifications(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the notifications + Constructs a ServiceContext - :returns: twilio.rest.notify.v1.service.notification.NotificationList - :rtype: twilio.rest.notify.v1.service.notification.NotificationList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.notifications + 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 4010c5a50d..33b1a4aac0 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -1,510 +1,681 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Service that the resource is associated with + """ + :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) + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def create(self, identity, binding_type, address, tag=values.unset, - notification_protocol_version=values.unset, - credential_sid=values.unset, endpoint=values.unset): + def delete(self) -> bool: """ - Create the BindingInstance + Deletes the BindingInstance - :param unicode identity: The `identity` value that identifies the new resource's User - :param BindingInstance.BindingType binding_type: The type of the Binding - :param unicode address: The channel-specific address - :param unicode tag: A tag that can be used to select the Bindings to notify - :param unicode notification_protocol_version: The protocol version to use to send the notification - :param unicode credential_sid: The SID of the Credential resource to be used to send notifications to this Binding - :param unicode endpoint: Deprecated - :returns: The created BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingInstance + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: """ - 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, - }) + Asynchronous coroutine that deletes the BindingInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return BindingInstance(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, start_date=values.unset, end_date=values.unset, - identity=values.unset, tag=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the BindingInstance - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param unicode identity: The `identity` value of the resources to read - :param unicode tag: Only list Bindings that have all of the specified Tags - :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: The fetched BindingInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - page_size=limits['page_size'], - ) + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance - return self._version.stream(page, limits['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 await self._proxy.fetch_async() - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param unicode identity: The `identity` value of the resources to read - :param unicode tag: Only list Bindings that have all of the specified Tags - :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] + def __repr__(self) -> str: """ - return list(self.stream( - start_date=start_date, - end_date=end_date, - identity=identity, - tag=tag, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - 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): + :returns: Machine friendly representation """ - Retrieve a single page of BindingInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param date start_date: Only include usage that has occurred on or after this date - :param date end_date: Only include usage that occurred on or before this date - :param unicode identity: The `identity` value of the resources to read - :param unicode tag: Only list Bindings that have all of the specified Tags - :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.notify.v1.service.binding.BindingPage +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): """ - 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, - }) + Initialize the BindingContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to fetch the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + super().__init__(version) - return BindingPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of BindingInstance records from the API. - Request is executed immediately + Deletes the BindingInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return BindingPage(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 BindingContext + Asynchronous coroutine that deletes the BindingInstance - :param sid: The unique string that identifies the resource - :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 __call__(self, sid): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: """ - Constructs a BindingContext + Fetch the BindingInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.notify.v1.service.binding.BindingContext - :rtype: twilio.rest.notify.v1.service.binding.BindingContext + :returns: The fetched BindingInstance """ - return BindingContext(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 BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: """ - Provide a friendly representation + Asynchronous coroutine to 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" - def __init__(self, version, response, solution): - """ - Initialize the BindingPage + 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 SID of the Service that the resource is associated with + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.notify.v1.service.binding.BindingPage - :rtype: twilio.rest.notify.v1.service.binding.BindingPage + def __repr__(self) -> str: """ - super(BindingPage, 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 BindingPage(Page): - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: """ Build an instance of BindingInstance - :param dict payload: Payload response from the API - - :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 SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource + :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) - - def fetch(self): + 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: """ - Fetch the BindingInstance + Create the BindingInstance - :returns: The fetched BindingInstance - :rtype: twilio.rest.notify.v1.service.binding.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return BindingInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], + 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 delete(self): - """ - Deletes the BindingInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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 BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Asynchronously create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -class BindingInstance(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 BindingType(object): - APN = "apn" - GCM = "gcm" - SMS = "sms" - FCM = "fcm" - FACEBOOK_MESSENGER = "facebook-messenger" - ALEXA = "alexa" + headers["Accept"] = "application/json" - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'credential_sid': payload.get('credential_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'notification_protocol_version': payload.get('notification_protocol_version'), - 'endpoint': payload.get('endpoint'), - 'identity': payload.get('identity'), - 'binding_type': payload.get('binding_type'), - 'address': payload.get('address'), - 'tags': payload.get('tags'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + 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 BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the 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. - :returns: BindingContext for this BindingInstance - :rtype: twilio.rest.notify.v1.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 + :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 sid(self): - """ - :returns: The unique string that identifies the resource - :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( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): + 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]: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + 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 credential_sid(self): - """ - :returns: The SID of the Credential resource to be used to send notifications to this Binding - :rtype: unicode - """ - return self._properties['credential_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 date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the 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 = await self.page_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return self._version.stream_async(page, limits["limit"]) - @property - def notification_protocol_version(self): + 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]: """ - :returns: The protocol version to use to send the notification - :rtype: unicode - """ - return self._properties['notification_protocol_version'] + 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 endpoint(self): - """ - :returns: Deprecated - :rtype: unicode - """ - return self._properties['endpoint'] + :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, + ) + ) - @property - def identity(self): - """ - :returns: The `identity` value that identifies the new resource's User - :rtype: unicode - """ - return self._properties['identity'] + 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 binding_type(self): - """ - :returns: The type of the Binding - :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['binding_type'] + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately - @property - def address(self): - """ - :returns: The channel-specific address - :rtype: unicode - """ - return self._properties['address'] + :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 tags(self): + :returns: Page of BindingInstance """ - :returns: The list of tags associated with this Binding - :rtype: unicode + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance """ - return self._properties['tags'] + 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 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 absolute URL of the Binding resource - :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 URLs of related resources - :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 the BindingInstance + Constructs a BindingContext - :returns: The 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 9ccac8e3d8..4d228e864f 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -1,357 +1,285 @@ -# coding=utf-8 r""" -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 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 SID of the Service that the resource is associated with - - :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, - delivery_callback_url=values.unset, identity=values.unset, - tag=values.unset): - """ - Create the NotificationInstance - - :param unicode body: The notification body text - :param NotificationInstance.Priority priority: The priority of the notification - :param unicode ttl: How long, in seconds, the notification is valid - :param unicode title: The notification title - :param unicode sound: The name of the sound to be played for the notification - :param unicode action: The actions to display for the notification - :param dict data: The custom key-value pairs of the notification's payload - :param dict apn: The APNS-specific payload that overrides corresponding attributes in a generic payload for APNS Bindings - :param dict gcm: The GCM-specific payload that overrides corresponding attributes in generic payload for GCM Bindings - :param dict sms: The SMS-specific payload that overrides corresponding attributes in generic payload for SMS Bindings - :param dict facebook_messenger: Deprecated - :param dict fcm: The FCM-specific payload that overrides corresponding attributes in generic payload for FCM Bindings - :param unicode segment: A Segment to notify - :param dict alexa: Deprecated - :param unicode to_binding: The destination address specified as a JSON string - :param unicode delivery_callback_url: URL to send webhooks - :param unicode identity: The `identity` value that identifies the new resource's User - :param unicode tag: A tag that selects the Bindings to notify - - :returns: The 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), - 'DeliveryCallbackUrl': delivery_callback_url, - }) - - payload = self._version.create(method='POST', uri=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 '' - + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ -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 SID of the Service that the resource is associated with - - :returns: twilio.rest.notify.v1.service.notification.NotificationPage - :rtype: twilio.rest.notify.v1.service.notification.NotificationPage - """ - super(NotificationPage, self).__init__(version, response) + Twilio - Notify + This is the public Twilio REST API. - # 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'], ) + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - def __repr__(self): - """ - Provide a friendly representation +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values - :returns: Machine friendly representation - :rtype: str - """ - return '' +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +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 - - :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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'identities': payload.get('identities'), - 'tags': payload.get('tags'), - 'segments': payload.get('segments'), - 'priority': payload.get('priority'), - 'ttl': deserialize.integer(payload.get('ttl')), - 'title': payload.get('title'), - 'body': payload.get('body'), - 'sound': payload.get('sound'), - 'action': payload.get('action'), - 'data': payload.get('data'), - 'apn': payload.get('apn'), - 'gcm': payload.get('gcm'), - 'fcm': payload.get('fcm'), - 'sms': payload.get('sms'), - 'facebook_messenger': payload.get('facebook_messenger'), - 'alexa': payload.get('alexa'), + """ + :ivar sid: The unique string that we created to identify the Notification resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar identities: The list of `identity` values of the Users to notify. We will attempt to deliver notifications only to Bindings with an identity in this list. + :ivar tags: The tags that select the Bindings to notify. Notifications will be attempted only to Bindings that have all of the tags listed in this property. + :ivar segments: The list of Segments to notify. The [Segment](https://www.twilio.com/docs/notify/api/segment-resource) resource is deprecated. Use the `tags` property, instead. + :ivar priority: + :ivar ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :ivar title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :ivar body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :ivar sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :ivar action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :ivar sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :ivar facebook_messenger: Deprecated. + :ivar alexa: Deprecated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.identities: Optional[List[str]] = payload.get("identities") + self.tags: Optional[List[str]] = payload.get("tags") + self.segments: Optional[List[str]] = payload.get("segments") + self.priority: Optional["NotificationInstance.Priority"] = payload.get( + "priority" + ) + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.sound: Optional[str] = payload.get("sound") + self.action: Optional[str] = payload.get("action") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.apn: Optional[Dict[str, object]] = payload.get("apn") + self.gcm: Optional[Dict[str, object]] = payload.get("gcm") + self.fcm: Optional[Dict[str, object]] = payload.get("fcm") + self.sms: Optional[Dict[str, object]] = payload.get("sms") + self.facebook_messenger: Optional[Dict[str, object]] = payload.get( + "facebook_messenger" + ) + self.alexa: Optional[Dict[str, object]] = payload.get("alexa") + + self._solution = { + "service_sid": service_sid, } - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def identities(self): - """ - :returns: The list of identity values of the Users to notify - :rtype: unicode - """ - return self._properties['identities'] - - @property - def tags(self): - """ - :returns: The tags that select the Bindings to notify - :rtype: unicode - """ - return self._properties['tags'] - - @property - def segments(self): - """ - :returns: The list of Segments to notify - :rtype: unicode - """ - return self._properties['segments'] - - @property - def priority(self): - """ - :returns: The priority of the notification - :rtype: NotificationInstance.Priority - """ - return self._properties['priority'] - - @property - def ttl(self): - """ - :returns: How long, in seconds, the notification is valid - :rtype: unicode - """ - return self._properties['ttl'] + Provide a friendly representation - @property - def title(self): - """ - :returns: The notification title - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['title'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def body(self): - """ - :returns: The notification body text - :rtype: unicode - """ - return self._properties['body'] - @property - def sound(self): - """ - :returns: The name of the sound to be played for the notification - :rtype: unicode - """ - return self._properties['sound'] +class NotificationList(ListResource): - @property - def action(self): - """ - :returns: The actions to display for the notification - :rtype: unicode + def __init__(self, version: Version, service_sid: str): """ - return self._properties['action'] + Initialize the NotificationList - @property - def data(self): - """ - :returns: The custom key-value pairs of the notification's payload - :rtype: dict - """ - return self._properties['data'] + :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 apn(self): - """ - :returns: The APNS-specific payload that overrides corresponding attributes in a generic payload for APNS Bindings - :rtype: dict """ - return self._properties['apn'] + super().__init__(version) - @property - def gcm(self): - """ - :returns: The GCM-specific payload that overrides corresponding attributes in generic payload for GCM Bindings - :rtype: dict + # 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: """ - return self._properties['gcm'] + Create the NotificationInstance - @property - def fcm(self): - """ - :returns: The FCM-specific payload that overrides corresponding attributes in generic payload for FCM Bindings - :rtype: dict - """ - return self._properties['fcm'] + :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. - @property - def sms(self): - """ - :returns: The SMS-specific payload that overrides corresponding attributes in generic payload for SMS Bindings - :rtype: dict + :returns: The created NotificationInstance """ - return self._properties['sms'] - @property - def facebook_messenger(self): - """ - :returns: Deprecated - :rtype: dict - """ - return self._properties['facebook_messenger'] + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. - @property - def alexa(self): - """ - :returns: Deprecated - :rtype: dict + :returns: The created NotificationInstance """ - return self._properties['alexa'] - def __repr__(self): + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" 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 index ec01621114..abe9985d75 100644 --- a/twilio/rest/numbers/__init__.py +++ b/twilio/rest/numbers/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.numbers.v2 import V2 +from twilio.rest.numbers.NumbersBase import NumbersBase +from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList -class Numbers(Domain): - - def __init__(self, twilio): - """ - Initialize the Numbers Domain - - :returns: Domain for Numbers - :rtype: twilio.rest.numbers.Numbers - """ - super(Numbers, self).__init__(twilio) - - self.base_url = 'https://numbers.twilio.com' - - # Versions - self._v2 = None - +class Numbers(NumbersBase): @property - def v2(self): - """ - :returns: Version v2 of numbers - :rtype: twilio.rest.numbers.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 - - @property - def regulatory_compliance(self): - """ - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceList - """ + def regulatory_compliance(self) -> RegulatoryComplianceList: + warn( + "regulatory_compliance is deprecated. Use v2.regulatory_compliance instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.regulatory_compliance - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' 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 index ad0251f460..04b303486e 100644 --- a/twilio/rest/numbers/v2/__init__.py +++ b/twilio/rest/numbers/v2/__init__.py @@ -1,42 +1,75 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Numbers - :returns: V2 version of Numbers - :rtype: twilio.rest.numbers.v2.V2.V2 + :param domain: The Twilio.numbers domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._regulatory_compliance = None + 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 regulatory_compliance(self): - """ - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + 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 index ba8f0dadc9..189117d85c 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/__init__.py @@ -1,189 +1,113 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.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.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 +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): + def __init__(self, version: Version): """ Initialize the RegulatoryComplianceList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceList """ - super(RegulatoryComplianceList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/RegulatoryCompliance" - # Components - self._bundles = None - self._end_users = None - self._end_user_types = None - self._regulations = None - self._supporting_documents = None - self._supporting_document_types = None + 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): + def bundles(self) -> BundleList: """ Access the bundles - - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList """ if self._bundles is None: - self._bundles = BundleList(self._version, ) + self._bundles = BundleList(self._version) return self._bundles @property - def end_users(self): + def end_users(self) -> EndUserList: """ Access the end_users - - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList """ if self._end_users is None: - self._end_users = EndUserList(self._version, ) + self._end_users = EndUserList(self._version) return self._end_users @property - def end_user_types(self): + def end_user_types(self) -> EndUserTypeList: """ Access the end_user_types - - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList """ if self._end_user_types is None: - self._end_user_types = EndUserTypeList(self._version, ) + self._end_user_types = EndUserTypeList(self._version) return self._end_user_types @property - def regulations(self): + def regulations(self) -> RegulationList: """ Access the regulations - - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList """ if self._regulations is None: - self._regulations = RegulationList(self._version, ) + self._regulations = RegulationList(self._version) return self._regulations @property - def supporting_documents(self): + def supporting_documents(self) -> SupportingDocumentList: """ Access the supporting_documents - - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList """ if self._supporting_documents is None: - self._supporting_documents = SupportingDocumentList(self._version, ) + self._supporting_documents = SupportingDocumentList(self._version) return self._supporting_documents @property - def supporting_document_types(self): + def supporting_document_types(self) -> SupportingDocumentTypeList: """ Access the supporting_document_types - - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList """ if self._supporting_document_types is None: - self._supporting_document_types = SupportingDocumentTypeList(self._version, ) + self._supporting_document_types = SupportingDocumentTypeList(self._version) return self._supporting_document_types - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RegulatoryCompliancePage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the RegulatoryCompliancePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryCompliancePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryCompliancePage - """ - super(RegulatoryCompliancePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of RegulatoryComplianceInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceInstance - """ - return RegulatoryComplianceInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class RegulatoryComplianceInstance(InstanceResource): - """ """ - - def __init__(self, version, payload): - """ - Initialize the RegulatoryComplianceInstance - - :returns: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.RegulatoryComplianceInstance - """ - super(RegulatoryComplianceInstance, self).__init__(version) - - # Context - self._context = None - 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/numbers/v2/regulatory_compliance/bundle/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py index 0f9f9e45b4..079540d87b 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -1,582 +1,1013 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.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.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 BundleList(ListResource): - """ """ +class BundleInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the BundleList + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" - :param Version version: Version that contains the resource + class SortBy(object): + VALID_UNTIL = "valid-until" + DATE_UPDATED = "date-updated" - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleList - """ - super(BundleList, self).__init__(version) + class SortDirection(object): + ASC = "ASC" + DESC = "DESC" - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/Bundles'.format(**self._solution) + 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" - def create(self, friendly_name, email, status_callback=values.unset, - regulation_sid=values.unset, iso_country=values.unset, - end_user_type=values.unset, number_type=values.unset): - """ - Create the BundleInstance + """ + :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") - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode email: The email address - :param unicode status_callback: The URL we call to inform your application of status changes. - :param unicode regulation_sid: The unique string of a regulation. - :param unicode iso_country: The ISO country code of the country - :param BundleInstance.EndUserType end_user_type: The type of End User of the Bundle resource - :param unicode number_type: The type of phone number + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[BundleContext] = None - :returns: The created BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + @property + def _proxy(self) -> "BundleContext": """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Email': email, - 'StatusCallback': status_callback, - 'RegulationSid': regulation_sid, - 'IsoCountry': iso_country, - 'EndUserType': end_user_type, - 'NumberType': number_type, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return BundleInstance(self._version, payload, ) + 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, status=values.unset, friendly_name=values.unset, - regulation_sid=values.unset, iso_country=values.unset, - number_type=values.unset, limit=None, page_size=None): + :returns: BundleContext for this 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 - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode regulation_sid: The unique string of a regulation. - :param unicode iso_country: The ISO country code of the country - :param unicode number_type: The type of phone number - :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 = BundleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the BundleInstance - page = self.page( - status=status, - friendly_name=friendly_name, - regulation_sid=regulation_sid, - iso_country=iso_country, - number_type=number_type, - page_size=limits['page_size'], - ) - return self._version.stream(page, limits['limit']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - def list(self, status=values.unset, friendly_name=values.unset, - regulation_sid=values.unset, iso_country=values.unset, - number_type=values.unset, limit=None, page_size=None): + async def delete_async(self) -> bool: """ - Lists BundleInstance 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 BundleInstance - :param BundleInstance.Status status: The verification status of the Bundle resource - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode regulation_sid: The unique string of a regulation. - :param unicode iso_country: The ISO country code of the country - :param unicode number_type: The type of phone number - :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.numbers.v2.regulatory_compliance.bundle.BundleInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - status=status, - friendly_name=friendly_name, - regulation_sid=regulation_sid, - iso_country=iso_country, - number_type=number_type, - limit=limit, - page_size=page_size, - )) + return await self._proxy.delete_async() - def page(self, status=values.unset, friendly_name=values.unset, - regulation_sid=values.unset, iso_country=values.unset, - number_type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def fetch(self) -> "BundleInstance": """ - Retrieve a single page of BundleInstance records from the API. - Request is executed immediately + Fetch the BundleInstance - :param BundleInstance.Status status: The verification status of the Bundle resource - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode regulation_sid: The unique string of a regulation. - :param unicode iso_country: The ISO country code of the country - :param unicode number_type: The type of phone number - :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 BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundlePage + :returns: The fetched BundleInstance """ - data = values.of({ - 'Status': status, - 'FriendlyName': friendly_name, - 'RegulationSid': regulation_sid, - 'IsoCountry': iso_country, - 'NumberType': number_type, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "BundleInstance": + """ + Asynchronous coroutine to fetch the BundleInstance - return BundlePage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched BundleInstance """ - Retrieve a specific page of BundleInstance 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: 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 - :returns: Page of BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundlePage + :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 """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, ) - return BundlePage(self._version, response, self._solution) - - def get(self, 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": """ - Constructs a BundleContext + Asynchronous coroutine to update the BundleInstance - :param sid: The unique string that identifies the resource. + :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: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + :returns: The updated BundleInstance """ - return BundleContext(self._version, sid=sid, ) + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) - def __call__(self, sid): + @property + def bundle_copies(self) -> BundleCopyList: """ - Constructs a BundleContext + Access the bundle_copies + """ + return self._proxy.bundle_copies - :param sid: The unique string that identifies the resource. + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + return self._proxy.evaluations - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments """ - return BundleContext(self._version, sid=sid, ) + return self._proxy.item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + return self._proxy.replace_items - 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 BundlePage(Page): - """ """ +class BundleContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the BundlePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the BundleContext - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundlePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundlePage + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Bundle resource. """ - super(BundlePage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BundleInstance + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._bundle_copies: Optional[BundleCopyList] = None + self._evaluations: Optional[EvaluationList] = None + self._item_assignments: Optional[ItemAssignmentList] = None + self._replace_items: Optional[ReplaceItemsList] = None - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + def delete(self) -> bool: """ - return BundleInstance(self._version, payload, ) + Deletes the BundleInstance - 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 BundleContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the BundleContext + Asynchronous coroutine that deletes the BundleInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource. - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + :returns: True if delete succeeds, False otherwise """ - super(BundleContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/Bundles/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._evaluations = None - self._item_assignments = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> BundleInstance: """ Fetch the BundleInstance + :returns: The fetched BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return BundleInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def update(self, status=values.unset, status_callback=values.unset, - friendly_name=values.unset, email=values.unset): - """ - Update the BundleInstance + headers["Accept"] = "application/json" - :param BundleInstance.Status status: The verification status of the Bundle resource - :param unicode status_callback: The URL we call to inform your application of status changes. - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode email: The email address + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: The updated BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance - """ - data = values.of({ - 'Status': status, - 'StatusCallback': status_callback, - 'FriendlyName': friendly_name, - 'Email': email, - }) + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + async def fetch_async(self) -> BundleInstance: + """ + Asynchronous coroutine to fetch the BundleInstance - return BundleInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): + :returns: The fetched BundleInstance """ - Deletes the BundleInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + headers = values.of({}) - @property - def evaluations(self): - """ - Access the evaluations + headers["Accept"] = "application/json" - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList - """ - if self._evaluations is None: - self._evaluations = EvaluationList(self._version, bundle_sid=self._solution['sid'], ) - return self._evaluations + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - @property - def item_assignments(self): - """ - Access the item_assignments + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList + 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: """ - if self._item_assignments is None: - self._item_assignments = ItemAssignmentList(self._version, bundle_sid=self._solution['sid'], ) - return self._item_assignments + Update the BundleInstance - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: The updated BundleInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) -class BundleInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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" - - class EndUserType(object): - INDIVIDUAL = "individual" - BUSINESS = "business" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): - """ - Initialize the BundleInstance - - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance - """ - super(BundleInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'regulation_sid': payload.get('regulation_sid'), - 'friendly_name': payload.get('friendly_name'), - 'status': payload.get('status'), - 'valid_until': deserialize.iso8601_datetime(payload.get('valid_until')), - 'email': payload.get('email'), - 'status_callback': payload.get('status_callback'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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 BundleInstance(self._version, payload, sid=self._solution["sid"]) - @property - def _proxy(self): + 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: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Asynchronous coroutine to update the BundleInstance - :returns: BundleContext for this BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleContext + :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 """ - if self._context is None: - self._context = BundleContext(self._version, sid=self._solution['sid'], ) - return self._context + + 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 sid(self): + def bundle_copies(self) -> BundleCopyList: """ - :returns: The unique string that identifies the resource. - :rtype: unicode + Access the bundle_copies """ - return self._properties['sid'] + if self._bundle_copies is None: + self._bundle_copies = BundleCopyList( + self._version, + self._solution["sid"], + ) + return self._bundle_copies @property - def account_sid(self): + def evaluations(self) -> EvaluationList: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + Access the evaluations """ - return self._properties['account_sid'] + if self._evaluations is None: + self._evaluations = EvaluationList( + self._version, + self._solution["sid"], + ) + return self._evaluations @property - def regulation_sid(self): + def item_assignments(self) -> ItemAssignmentList: """ - :returns: The unique string of a regulation. - :rtype: unicode + Access the item_assignments """ - return self._properties['regulation_sid'] + if self._item_assignments is None: + self._item_assignments = ItemAssignmentList( + self._version, + self._solution["sid"], + ) + return self._item_assignments @property - def friendly_name(self): + def replace_items(self) -> ReplaceItemsList: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + Access the replace_items """ - return self._properties['friendly_name'] + if self._replace_items is None: + self._replace_items = ReplaceItemsList( + self._version, + self._solution["sid"], + ) + return self._replace_items - @property - def status(self): + def __repr__(self) -> str: """ - :returns: The verification status of the Bundle resource - :rtype: BundleInstance.Status + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['status'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def valid_until(self): + +class BundlePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: """ - :returns: The ISO 8601 date and time in GMT when the resource will be valid until. - :rtype: datetime + Build an instance of BundleInstance + + :param payload: Payload response from the API """ - return self._properties['valid_until'] + return BundleInstance(self._version, payload) - @property - def email(self): + def __repr__(self) -> str: """ - :returns: The email address - :rtype: unicode + Provide a friendly representation + + :returns: Machine friendly representation """ - return self._properties['email'] + return "" - @property - def status_callback(self): + +class BundleList(ListResource): + + def __init__(self, version: Version): """ - :returns: The URL we call to inform your application of status changes. - :rtype: unicode + Initialize the BundleList + + :param version: Version that contains the resource + """ - return self._properties['status_callback'] + super().__init__(version) - @property - def date_created(self): + 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: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] - @property - def date_updated(self): + 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 """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + + 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]: """ - return self._properties['date_updated'] + 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. - @property - def url(self): + :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 """ - :returns: The absolute URL of the Bundle resource - :rtype: unicode + 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 """ - return self._properties['url'] + 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"], + ) - @property - def links(self): + 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]: """ - :returns: The URLs of the Assigned Items of the Bundle resource - :rtype: unicode + 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: """ - return self._properties['links'] + Retrieve a single page of BundleInstance records from the API. + Request is executed immediately - def fetch(self): + :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 """ - Fetch the 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, + } + ) - :returns: The fetched BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + headers = values.of({"Content-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 """ - return self._proxy.fetch() + 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, + } + ) - def update(self, status=values.unset, status_callback=values.unset, - friendly_name=values.unset, email=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 BundlePage(self._version, response) + + def get_page(self, target_url: str) -> BundlePage: """ - Update the BundleInstance + Retrieve a specific page of BundleInstance records from the API. + Request is executed immediately - :param BundleInstance.Status status: The verification status of the Bundle resource - :param unicode status_callback: The URL we call to inform your application of status changes. - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode email: The email address + :param target_url: API-generated URL for the requested results page - :returns: The updated BundleInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.BundleInstance + :returns: Page of BundleInstance """ - return self._proxy.update( - status=status, - status_callback=status_callback, - friendly_name=friendly_name, - email=email, - ) + response = self._version.domain.twilio.request("GET", target_url) + return BundlePage(self._version, response) - def delete(self): + async def get_page_async(self, target_url: str) -> BundlePage: """ - Deletes the BundleInstance + Asynchronously retrieve a specific page of BundleInstance 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 BundleInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundlePage(self._version, response) - @property - def evaluations(self): + def get(self, sid: str) -> BundleContext: """ - Access the evaluations + Constructs a BundleContext - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList + :param sid: The unique string that we created to identify the Bundle resource. """ - return self._proxy.evaluations + return BundleContext(self._version, sid=sid) - @property - def item_assignments(self): + def __call__(self, sid: str) -> BundleContext: """ - Access the item_assignments + Constructs a BundleContext - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList + :param sid: The unique string that we created to identify the Bundle resource. """ - return self._proxy.item_assignments + return BundleContext(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/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 index fcc1cc0631..fd45064808 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -1,373 +1,487 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 EvaluationList(ListResource): - """ """ +class EvaluationInstance(InstanceResource): - def __init__(self, version, bundle_sid): + 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": """ - Initialize the EvaluationList + 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 bundle_sid: The unique string that identifies the resource + :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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationList + def fetch(self) -> "EvaluationInstance": """ - super(EvaluationList, self).__init__(version) + Fetch the EvaluationInstance - # Path Solution - self._solution = {'bundle_sid': bundle_sid, } - self._uri = '/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations'.format(**self._solution) - def create(self): + :returns: The fetched EvaluationInstance """ - Create the EvaluationInstance + return self._proxy.fetch() - :returns: The created EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance + async def fetch_async(self) -> "EvaluationInstance": """ - payload = self._version.create(method='POST', uri=self._uri, ) + Asynchronous coroutine to fetch the EvaluationInstance - return EvaluationInstance(self._version, payload, bundle_sid=self._solution['bundle_sid'], ) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_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) + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance] + :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']) +class EvaluationContext(InstanceContext): - def list(self, limit=None, page_size=None): + def __init__(self, version: Version, bundle_sid: str, sid: str): """ - 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 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) + Initialize the EvaluationContext - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance] + :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. """ - return list(self.stream(limit=limit, page_size=page_size, )) + 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 page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> EvaluationInstance: """ - Retrieve a single page of EvaluationInstance records from the API. - Request is executed immediately + Fetch the EvaluationInstance - :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 EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationPage + :returns: The fetched EvaluationInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + headers = values.of({}) - return EvaluationPage(self._version, response, self._solution) + headers["Accept"] = "application/json" - def get_page(self, target_url): - """ - Retrieve a specific page of EvaluationInstance records from the API. - Request is executed immediately + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param str target_url: API-generated URL for the requested results page + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) - :returns: Page of EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationPage + async def fetch_async(self) -> EvaluationInstance: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the EvaluationInstance - return EvaluationPage(self._version, response, self._solution) - def get(self, sid): + :returns: The fetched EvaluationInstance """ - Constructs a EvaluationContext - :param sid: The unique string that identifies the Evaluation resource + 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"], + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext + def __repr__(self) -> str: """ - return EvaluationContext(self._version, bundle_sid=self._solution['bundle_sid'], sid=sid, ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a EvaluationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the Evaluation resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext +class EvaluationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: """ - return EvaluationContext(self._version, bundle_sid=self._solution['bundle_sid'], sid=sid, ) + Build an instance of EvaluationInstance - def __repr__(self): + :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 - :rtype: str """ - return '' + return "" -class EvaluationPage(Page): - """ """ +class EvaluationList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, bundle_sid: str): """ - Initialize the EvaluationPage + Initialize the EvaluationList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param bundle_sid: The unique string that identifies the resource + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle resource. - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationPage """ - super(EvaluationPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations".format( + **self._solution + ) - def get_instance(self, payload): + def create(self) -> EvaluationInstance: """ - Build an instance of EvaluationInstance + Create the EvaluationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance + :returns: The created EvaluationInstance """ - return EvaluationInstance(self._version, payload, bundle_sid=self._solution['bundle_sid'], ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.create(method="POST", uri=self._uri, headers=headers) -class EvaluationContext(InstanceContext): - """ """ + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) - def __init__(self, version, bundle_sid, sid): + async def create_async(self) -> EvaluationInstance: """ - Initialize the EvaluationContext + Asynchronously create the EvaluationInstance - :param Version version: Version that contains the resource - :param bundle_sid: The unique string that identifies the resource - :param sid: The unique string that identifies the Evaluation resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext + :returns: The created EvaluationInstance """ - super(EvaluationContext, self).__init__(version) - # Path Solution - self._solution = {'bundle_sid': bundle_sid, 'sid': sid, } - self._uri = '/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations/{sid}'.format(**self._solution) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def fetch(self): - """ - Fetch the EvaluationInstance + headers["Accept"] = "application/json" - :returns: The fetched EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) return EvaluationInstance( - self._version, - payload, - bundle_sid=self._solution['bundle_sid'], - sid=self._solution['sid'], + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - def __repr__(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EvaluationInstance]: """ - Provide a friendly representation + 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. - :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 = self.page(page_size=limits["page_size"]) + return self._version.stream(page, limits["limit"]) -class EvaluationInstance(InstanceResource): - """ """ + 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. - class Status(object): - COMPLIANT = "compliant" - NONCOMPLIANT = "noncompliant" + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, bundle_sid, sid=None): + :returns: Generator that will yield up to limit results """ - Initialize the EvaluationInstance + limits = self._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.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: """ - super(EvaluationInstance, self).__init__(version) + Lists EvaluationInstance 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'regulation_sid': payload.get('regulation_sid'), - 'bundle_sid': payload.get('bundle_sid'), - 'status': payload.get('status'), - 'results': payload.get('results'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'url': payload.get('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 = {'bundle_sid': bundle_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[EvaluationInstance]: """ - 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 EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: EvaluationContext for this EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = EvaluationContext( - self._version, - bundle_sid=self._solution['bundle_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 unique string that identifies the Evaluation resource - :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, + ) -> EvaluationPage: """ - return self._properties['sid'] + Retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 regulation_sid(self): - """ - :returns: The unique string of a regulation - :rtype: unicode + :returns: Page of EvaluationInstance """ - return self._properties['regulation_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def bundle_sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['bundle_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status(self): + 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: """ - :returns: The compliance status of the Evaluation resource - :rtype: EvaluationInstance.Status + 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 """ - return self._properties['status'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def results(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 EvaluationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EvaluationPage: """ - :returns: The results of the Evaluation resource - :rtype: dict + 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 """ - return self._properties['results'] + response = self._version.domain.twilio.request("GET", target_url) + return EvaluationPage(self._version, response, self._solution) - @property - def date_created(self): + async def get_page_async(self, target_url: str) -> EvaluationPage: """ - :returns: The date_created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EvaluationPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> EvaluationContext: """ - :returns: The url - :rtype: unicode + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. """ - return self._properties['url'] + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> EvaluationContext: """ - Fetch the EvaluationInstance + Constructs a EvaluationContext - :returns: The fetched EvaluationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation.EvaluationInstance + :param sid: The unique string that identifies the Evaluation resource. """ - return self._proxy.fetch() + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_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/numbers/v2/regulatory_compliance/bundle/item_assignment.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py index ed2656a7c3..4eb1fe2b33 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -1,373 +1,540 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 ItemAssignmentList(ListResource): - """ """ +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 - def __init__(self, version, bundle_sid): + @property + def _proxy(self) -> "ItemAssignmentContext": """ - Initialize the ItemAssignmentList + 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 bundle_sid: The unique string that identifies the Bundle resource. + :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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentList + def delete(self) -> bool: """ - super(ItemAssignmentList, self).__init__(version) + Deletes the ItemAssignmentInstance - # Path Solution - self._solution = {'bundle_sid': bundle_sid, } - self._uri = '/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments'.format(**self._solution) - def create(self, object_sid): + :returns: True if delete succeeds, False otherwise """ - Create the ItemAssignmentInstance - - :param unicode object_sid: The sid of an object bag + return self._proxy.delete() - :returns: The created ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + async def delete_async(self) -> bool: """ - data = values.of({'ObjectSid': object_sid, }) + Asynchronous coroutine that deletes the ItemAssignmentInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return ItemAssignmentInstance(self._version, payload, bundle_sid=self._solution['bundle_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) -> "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. + Fetch the ItemAssignmentInstance - :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.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance] + :returns: The fetched ItemAssignmentInstance """ - 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) -> "ItemAssignmentInstance": + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance] + 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 ItemAssignmentInstance 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 ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage +class ItemAssignmentContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the ItemAssignmentContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return ItemAssignmentPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}".format( + **self._solution + ) + ) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of ItemAssignmentInstance records from the API. - Request is executed immediately + Deletes the ItemAssignmentInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return ItemAssignmentPage(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 ItemAssignmentContext + Asynchronous coroutine that deletes the ItemAssignmentInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext + :returns: True if delete succeeds, False otherwise """ - return ItemAssignmentContext(self._version, bundle_sid=self._solution['bundle_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) -> ItemAssignmentInstance: """ - Constructs a ItemAssignmentContext + Fetch the ItemAssignmentInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext + :returns: The fetched ItemAssignmentInstance """ - return ItemAssignmentContext(self._version, bundle_sid=self._solution['bundle_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 ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ItemAssignmentInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ItemAssignmentInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched ItemAssignmentInstance """ - return '' + headers = values.of({}) -class ItemAssignmentPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the ItemAssignmentPage + 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"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param bundle_sid: The unique string that identifies the Bundle resource. + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentPage + :returns: Machine friendly representation """ - super(ItemAssignmentPage, 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 ItemAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: """ Build an instance of ItemAssignmentInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + :param payload: Payload response from the API """ - return ItemAssignmentInstance(self._version, payload, bundle_sid=self._solution['bundle_sid'], ) + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ItemAssignmentContext(InstanceContext): - """ """ +class ItemAssignmentList(ListResource): - def __init__(self, version, bundle_sid, sid): + def __init__(self, version: Version, bundle_sid: str): """ - Initialize the ItemAssignmentContext + Initialize the ItemAssignmentList - :param Version version: Version that contains the resource - :param bundle_sid: The unique string that identifies the resource. - :param sid: The unique string that identifies the resource + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext """ - super(ItemAssignmentContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'bundle_sid': bundle_sid, 'sid': sid, } - self._uri = '/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}'.format(**self._solution) + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments".format( + **self._solution + ) - def fetch(self): + def create(self, object_sid: str) -> ItemAssignmentInstance: """ - Fetch the ItemAssignmentInstance + Create the ItemAssignmentInstance - :returns: The fetched ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - def delete(self): + async def create_async(self, object_sid: str) -> ItemAssignmentInstance: """ - Deletes the ItemAssignmentInstance + Asynchronously create the ItemAssignmentInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + :param object_sid: The SID of an object bag that holds information of the different items. - def __repr__(self): + :returns: The created ItemAssignmentInstance """ - Provide 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( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/x-www-form-urlencoded" -class ItemAssignmentInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload, bundle_sid, sid=None): - """ - Initialize the ItemAssignmentInstance + 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"] + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ItemAssignmentInstance]: """ - super(ItemAssignmentInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'bundle_sid': payload.get('bundle_sid'), - 'account_sid': payload.get('account_sid'), - 'object_sid': payload.get('object_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'url': payload.get('url'), - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = {'bundle_sid': bundle_sid, 'sid': sid or self._properties['sid'], } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def _proxy(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ItemAssignmentInstance]: """ - 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 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. - :returns: ItemAssignmentContext for this ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = ItemAssignmentContext( - self._version, - bundle_sid=self._solution['bundle_sid'], - sid=self._solution['sid'], - ) - return self._context + 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[ItemAssignmentInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 self._properties['sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def bundle_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: """ - :returns: The unique string that identifies the Bundle resource. - :rtype: unicode + 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 self._properties['bundle_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, + ) -> ItemAssignmentPage: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def object_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 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: """ - :returns: The sid of an object bag - :rtype: unicode + 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 """ - return self._properties['object_sid'] + 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 ItemAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ItemAssignmentPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> ItemAssignmentPage: """ - :returns: The absolute URL of the Identity resource - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ItemAssignmentContext: """ - Fetch the ItemAssignmentInstance + Constructs a ItemAssignmentContext - :returns: The fetched ItemAssignmentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment.ItemAssignmentInstance + :param sid: The unique string that we created to identify the Identity resource. """ - return self._proxy.fetch() + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) - def delete(self): + def __call__(self, sid: str) -> ItemAssignmentContext: """ - Deletes the ItemAssignmentInstance + Constructs a ItemAssignmentContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique string that we created to identify the Identity resource. """ - return self._proxy.delete() + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_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/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 index 7a39c1daab..ab1803372a 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -1,400 +1,638 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 EndUserList(ListResource): - """ """ +class EndUserInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the EndUserList + class Type(object): + INDIVIDUAL = "individual" + BUSINESS = "business" - :param Version version: Version that contains the resource + """ + :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") - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserList + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": """ - super(EndUserList, 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 = '/RegulatoryCompliance/EndUsers'.format(**self._solution) + :returns: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, friendly_name, type, attributes=values.unset): + def delete(self) -> bool: """ - Create the EndUserInstance + Deletes the EndUserInstance - :param unicode friendly_name: The string that you assigned to describe the resource - :param EndUserInstance.Type type: The type of end user of the Bundle resource - :param dict attributes: The set of parameters that compose the End User resource - :returns: The created EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Attributes': serialize.object(attributes), - }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance - return EndUserInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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.numbers.v2.regulatory_compliance.end_user.EndUserInstance] + def fetch(self) -> "EndUserInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the EndUserInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched EndUserInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the EndUserInstance - :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.numbers.v2.regulatory_compliance.end_user.EndUserInstance] + :returns: The fetched EndUserInstance """ - 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, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": """ - Retrieve a single page of EndUserInstance records from the API. - Request is executed immediately + Update the EndUserInstance - :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: 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: Page of EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :returns: The updated EndUserInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return EndUserPage(self._version, response, self._solution) + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) - def get_page(self, target_url): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": """ - Retrieve a specific page of EndUserInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the EndUserInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :returns: The updated EndUserInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, ) - return EndUserPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a EndUserContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The unique string that identifies the resource +class EndUserContext(InstanceContext): - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + def __init__(self, version: Version, sid: str): """ - return EndUserContext(self._version, sid=sid, ) + Initialize the EndUserContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. """ - Constructs a EndUserContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + def delete(self) -> bool: """ - return EndUserContext(self._version, sid=sid, ) + Deletes the EndUserInstance - 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 EndUserPage(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 EndUserPage + Asynchronous coroutine that deletes the EndUserInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserPage + :returns: True if delete succeeds, False otherwise """ - super(EndUserPage, 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) -> EndUserInstance: """ - Build an instance of EndUserInstance + Fetch the EndUserInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + :returns: The fetched EndUserInstance """ - return EndUserInstance(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 EndUserContext(InstanceContext): - """ """ + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> EndUserInstance: """ - Initialize the EndUserContext + Asynchronous coroutine to fetch the EndUserInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext + :returns: The fetched EndUserInstance """ - super(EndUserContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/EndUsers/{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 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: """ - Fetch the EndUserInstance + Update the EndUserInstance - :returns: The fetched EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return EndUserInstance(self._version, payload, sid=self._solution['sid'], ) + 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 + ) - def update(self, friendly_name=values.unset, attributes=values.unset): + 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: """ - Update the EndUserInstance + Asynchronous coroutine to update the EndUserInstance - :param unicode friendly_name: The string that you assigned to describe the resource - :param dict attributes: The set of parameters that compose the End User resource + :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 - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance """ - data = values.of({'FriendlyName': friendly_name, 'Attributes': serialize.object(attributes), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], ) + return EndUserInstance(self._version, payload, 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 EndUserInstance(InstanceResource): - """ """ +class EndUserPage(Page): - class Type(object): - INDIVIDUAL = "individual" - BUSINESS = "business" + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: + """ + Build an instance of EndUserInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the EndUserInstance + return EndUserInstance(self._version, payload) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + def __repr__(self) -> str: """ - super(EndUserInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'type': payload.get('type'), - 'attributes': payload.get('attributes'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } - @property - def _proxy(self): +class EndUserList(ListResource): + + 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 EndUserList + + :param version: Version that contains the resource - :returns: EndUserContext for this EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserContext """ - if self._context is None: - self._context = EndUserContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def sid(self): + self._uri = "/RegulatoryCompliance/EndUsers" + + def create( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def account_sid(self): + 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: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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 """ - 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[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 """ - :returns: The type of end user of the Bundle resource - :rtype: EndUserInstance.Type + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=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]: """ - return self._properties['type'] + Lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def attributes(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 set of parameters that compose the End Users resource - :rtype: dict + return 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]: """ - return self._properties['attributes'] + 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. - @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 + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - 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 = 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 """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 EndUserPage(self._version, response) + + def get_page(self, target_url: str) -> EndUserPage: """ - return self._properties['date_updated'] + Retrieve a specific page of EndUserInstance 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 EndUserInstance """ - :returns: The absolute URL of the End User resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return EndUserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of EndUserInstance """ - Fetch the EndUserInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserPage(self._version, response) - :returns: The fetched EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + def get(self, sid: str) -> EndUserContext: """ - return self._proxy.fetch() + Constructs a EndUserContext - def update(self, friendly_name=values.unset, attributes=values.unset): + :param sid: The unique string created by Twilio to identify the End User resource. """ - Update the EndUserInstance + return EndUserContext(self._version, sid=sid) - :param unicode friendly_name: The string that you assigned to describe the resource - :param dict attributes: The set of parameters that compose the End User resource + def __call__(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext - :returns: The updated EndUserInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user.EndUserInstance + :param sid: The unique string created by Twilio to identify the End User resource. """ - return self._proxy.update(friendly_name=friendly_name, attributes=attributes, ) + return EndUserContext(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/numbers/v2/regulatory_compliance/end_user_type.py b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py index bc5783d88a..f14c8905c7 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -1,318 +1,408 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 EndUserTypeList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "EndUserTypeContext": """ - Initialize the EndUserTypeList - - :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.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeList + :returns: EndUserTypeContext for this EndUserTypeInstance """ - super(EndUserTypeList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/EndUserTypes'.format(**self._solution) + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the EndUserTypeInstance - :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.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance] + :returns: The fetched EndUserTypeInstance """ - 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) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance] + 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 EndUserTypeInstance 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 EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage +class EndUserTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the EndUserTypeContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The unique string that identifies the End-User Type resource. + """ + super().__init__(version) - return EndUserTypePage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUserTypes/{sid}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> EndUserTypeInstance: """ - Retrieve a specific page of EndUserTypeInstance records from the API. - Request is executed immediately + Fetch the EndUserTypeInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage + :returns: The fetched EndUserTypeInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return EndUserTypePage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a EndUserTypeContext + headers["Accept"] = "application/json" - :param sid: The unique string that identifies the End-User Type resource + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - """ - return EndUserTypeContext(self._version, sid=sid, ) + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> EndUserTypeInstance: """ - Constructs a EndUserTypeContext + Asynchronous coroutine to fetch the EndUserTypeInstance - :param sid: The unique string that identifies the End-User Type resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext + :returns: The fetched EndUserTypeInstance """ - return EndUserTypeContext(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 EndUserTypePage(Page): - """ """ + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the EndUserTypePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypePage + :returns: Machine friendly representation """ - super(EndUserTypePage, 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 EndUserTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: """ Build an instance of EndUserTypeInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + :param payload: Payload response from the API """ - return EndUserTypeInstance(self._version, payload, ) + return EndUserTypeInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class EndUserTypeContext(InstanceContext): - """ """ +class EndUserTypeList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the EndUserTypeContext + Initialize the EndUserTypeList - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the End-User Type resource + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext """ - super(EndUserTypeContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/EndUserTypes/{sid}'.format(**self._solution) + self._uri = "/RegulatoryCompliance/EndUserTypes" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: """ - Fetch the 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. - :returns: The fetched EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return EndUserTypeInstance(self._version, payload, sid=self._solution['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[EndUserTypeInstance]: """ - Provide a friendly representation + 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. - :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 EndUserTypeInstance(InstanceResource): - """ """ + 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) - def __init__(self, version, payload, sid=None): + :returns: list that will contain up to limit results """ - Initialize the EndUserTypeInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: """ - super(EndUserTypeInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'machine_name': payload.get('machine_name'), - 'fields': payload.get('fields'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'sid': sid or self._properties['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 _proxy(self): + :returns: Page of EndUserTypeInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: EndUserTypeContext for this EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeContext - """ - if self._context is None: - self._context = EndUserTypeContext(self._version, sid=self._solution['sid'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sid(self): - """ - :returns: The unique string that identifies the End-User Type resource - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def friendly_name(self): + 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: """ - :returns: A human-readable description of the End-User Type resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def machine_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 EndUserTypePage(self._version, response) + + def get_page(self, target_url: str) -> EndUserTypePage: """ - :returns: A machine-readable description of the End-User Type resource - :rtype: unicode + 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 """ - return self._properties['machine_name'] + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) - @property - def fields(self): + async def get_page_async(self, target_url: str) -> EndUserTypePage: """ - :returns: The required information for creating an End-User. - :rtype: dict + 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 """ - return self._properties['fields'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserTypePage(self._version, response) - @property - def url(self): + def get(self, sid: str) -> EndUserTypeContext: """ - :returns: The absolute URL of the End-User Type resource - :rtype: unicode + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. """ - return self._properties['url'] + return EndUserTypeContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> EndUserTypeContext: """ - Fetch the EndUserTypeInstance + Constructs a EndUserTypeContext - :returns: The fetched EndUserTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.end_user_type.EndUserTypeInstance + :param sid: The unique string that identifies the End-User Type resource. """ - return self._proxy.fetch() + return EndUserTypeContext(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/numbers/v2/regulatory_compliance/regulation.py b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py index c08999b70b..9c1227905e 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -1,370 +1,525 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 RegulationList(ListResource): - """ """ +class RegulationInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the RegulationList + 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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RegulationContext] = None - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationList + @property + def _proxy(self) -> "RegulationContext": """ - super(RegulationList, 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 = '/RegulatoryCompliance/Regulations'.format(**self._solution) + :returns: RegulationContext for this RegulationInstance + """ + if self._context is None: + self._context = RegulationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, end_user_type=values.unset, iso_country=values.unset, - number_type=values.unset, limit=None, page_size=None): + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> "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. + Fetch the RegulationInstance - :param RegulationInstance.EndUserType end_user_type: The type of End User of the Regulation resource - :param unicode iso_country: The ISO country code of the phone number's country - :param unicode number_type: The type of phone number being regulated - :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 include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance] + :returns: The fetched RegulationInstance """ - 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, - page_size=limits['page_size'], + return self._proxy.fetch( + include_constraints=include_constraints, ) - return self._version.stream(page, limits['limit']) - - def list(self, end_user_type=values.unset, iso_country=values.unset, - number_type=values.unset, limit=None, page_size=None): + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> "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. + Asynchronous coroutine to fetch the RegulationInstance - :param RegulationInstance.EndUserType end_user_type: The type of End User of the Regulation resource - :param unicode iso_country: The ISO country code of the phone number's country - :param unicode number_type: The type of phone number being regulated - :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 include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance] + :returns: The fetched RegulationInstance """ - return list(self.stream( - end_user_type=end_user_type, - iso_country=iso_country, - number_type=number_type, - limit=limit, - page_size=page_size, - )) + return await self._proxy.fetch_async( + include_constraints=include_constraints, + ) - def page(self, end_user_type=values.unset, iso_country=values.unset, - number_type=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of RegulationInstance 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 RegulationInstance.EndUserType end_user_type: The type of End User of the Regulation resource - :param unicode iso_country: The ISO country code of the phone number's country - :param unicode number_type: The type of phone number being regulated - :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 RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationPage +class RegulationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'EndUserType': end_user_type, - 'IsoCountry': iso_country, - 'NumberType': number_type, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the RegulationContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The unique string that identifies the Regulation resource. + """ + super().__init__(version) - return RegulationPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) - def get_page(self, target_url): + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: """ - Retrieve a specific page of RegulationInstance records from the API. - Request is executed immediately + Fetch the RegulationInstance - :param str target_url: API-generated URL for the requested results page + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - :returns: Page of RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationPage + :returns: The fetched RegulationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } ) - return RegulationPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a RegulationContext + headers["Accept"] = "application/json" - :param sid: The unique string that identifies the Regulation resource + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - """ - return RegulationContext(self._version, sid=sid, ) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: """ - Constructs a RegulationContext + Asynchronous coroutine to fetch the RegulationInstance - :param sid: The unique string that identifies the Regulation resource + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext + :returns: The fetched RegulationInstance """ - return RegulationContext(self._version, sid=sid, ) - def __repr__(self): - """ - Provide a friendly representation + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({}) + headers["Accept"] = "application/json" -class RegulationPage(Page): - """ """ + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - def __init__(self, version, response, solution): - """ - Initialize the RegulationPage + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :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.numbers.v2.regulatory_compliance.regulation.RegulationPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationPage + :returns: Machine friendly representation """ - super(RegulationPage, 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 RegulationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: """ Build an instance of RegulationInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + :param payload: Payload response from the API """ - return RegulationInstance(self._version, payload, ) + return RegulationInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class RegulationContext(InstanceContext): - """ """ +class RegulationList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the RegulationContext + Initialize the RegulationList - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the Regulation resource + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext """ - super(RegulationContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/Regulations/{sid}'.format(**self._solution) + self._uri = "/RegulatoryCompliance/Regulations" - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + :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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 RegulationInstance(self._version, payload, sid=self._solution['sid'], ) + return self._version.stream(page, limits["limit"]) - def __repr__(self): + 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]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - 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_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"]) -class RegulationInstance(InstanceResource): - """ """ + 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. - class EndUserType(object): - INDIVIDUAL = "individual" - BUSINESS = "business" + :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. - def __init__(self, version, payload, sid=None): + :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: """ - Initialize the RegulationInstance + 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: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + :returns: Page of RegulationInstance """ - super(RegulationInstance, self).__init__(version) + 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, + } + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'iso_country': payload.get('iso_country'), - 'number_type': payload.get('number_type'), - 'end_user_type': payload.get('end_user_type'), - 'requirements': payload.get('requirements'), - 'url': payload.get('url'), - } + headers = values.of({"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 + 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 - :returns: RegulationContext for this RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationContext - """ - if self._context is None: - self._context = RegulationContext(self._version, sid=self._solution['sid'], ) - return self._context + :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 - @property - def sid(self): - """ - :returns: The unique string that identifies the Regulation resource - :rtype: unicode + :returns: Page of RegulationInstance """ - return self._properties['sid'] + 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, + } + ) - @property - def friendly_name(self): - """ - :returns: A human-readable description of the Regulation resource - :rtype: unicode - """ - return self._properties['friendly_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def iso_country(self): - """ - :returns: The ISO country code of the phone number's country - :rtype: unicode - """ - return self._properties['iso_country'] + headers["Accept"] = "application/json" - @property - def number_type(self): - """ - :returns: The type of phone number restricted by the regulatory requirement - :rtype: unicode - """ - return self._properties['number_type'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) - @property - def end_user_type(self): + def get_page(self, target_url: str) -> RegulationPage: """ - :returns: The type of End User of the Regulation resource - :rtype: RegulationInstance.EndUserType + 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 """ - return self._properties['end_user_type'] + response = self._version.domain.twilio.request("GET", target_url) + return RegulationPage(self._version, response) - @property - def requirements(self): + async def get_page_async(self, target_url: str) -> RegulationPage: """ - :returns: The sid of a regulation object that dictates requirements - :rtype: dict + 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 """ - return self._properties['requirements'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return RegulationPage(self._version, response) - @property - def url(self): + def get(self, sid: str) -> RegulationContext: """ - :returns: The absolute URL of the Regulation resource - :rtype: unicode + Constructs a RegulationContext + + :param sid: The unique string that identifies the Regulation resource. """ - return self._properties['url'] + return RegulationContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> RegulationContext: """ - Fetch the RegulationInstance + Constructs a RegulationContext - :returns: The fetched RegulationInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.regulation.RegulationInstance + :param sid: The unique string that identifies the Regulation resource. """ - return self._proxy.fetch() + return RegulationContext(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/numbers/v2/regulatory_compliance/supporting_document.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py index 6052dd448e..b72f993858 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -1,422 +1,658 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 SupportingDocumentList(ListResource): - """ """ +class SupportingDocumentInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the SupportingDocumentList + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + REJECTED = "rejected" + APPROVED = "approved" + EXPIRED = "expired" + PROVISIONALLY_APPROVED = "provisionally-approved" - :param Version version: Version that contains the resource + """ + :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 - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentList + @property + def _proxy(self) -> "SupportingDocumentContext": """ - super(SupportingDocumentList, 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 = '/RegulatoryCompliance/SupportingDocuments'.format(**self._solution) + :returns: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, friendly_name, type, attributes=values.unset): + def delete(self) -> bool: """ - Create the SupportingDocumentInstance + Deletes the SupportingDocumentInstance - :param unicode friendly_name: The string that you assigned to describe the resource - :param unicode type: The type of the Supporting Document - :param dict attributes: The set of parameters that compose the Supporting Documents resource - :returns: The created SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Type': type, - 'Attributes': serialize.object(attributes), - }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance - return SupportingDocumentInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 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.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance] + def fetch(self) -> "SupportingDocumentInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the SupportingDocumentInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched SupportingDocumentInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SupportingDocumentInstance - :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.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance] + :returns: The fetched SupportingDocumentInstance """ - 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, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": """ - Retrieve a single page of SupportingDocumentInstance records from the API. - Request is executed immediately + Update the SupportingDocumentInstance - :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: 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: Page of SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :returns: The updated SupportingDocumentInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SupportingDocumentPage(self._version, response, self._solution) + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) - def get_page(self, target_url): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": """ - Retrieve a specific page of SupportingDocumentInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SupportingDocumentInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :returns: The updated SupportingDocumentInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, ) - return SupportingDocumentPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a SupportingDocumentContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The unique string that identifies the resource +class SupportingDocumentContext(InstanceContext): - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + def __init__(self, version: Version, sid: str): """ - return SupportingDocumentContext(self._version, sid=sid, ) + Initialize the SupportingDocumentContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. """ - Constructs a SupportingDocumentContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocuments/{sid}".format( + **self._solution + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + def delete(self) -> bool: """ - return SupportingDocumentContext(self._version, sid=sid, ) + Deletes the SupportingDocumentInstance - 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 SupportingDocumentPage(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 SupportingDocumentPage + Asynchronous coroutine that deletes the SupportingDocumentInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentPage + :returns: True if delete succeeds, False otherwise """ - super(SupportingDocumentPage, 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) -> SupportingDocumentInstance: """ - Build an instance of SupportingDocumentInstance + Fetch the SupportingDocumentInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + :returns: The fetched SupportingDocumentInstance """ - return SupportingDocumentInstance(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 SupportingDocumentContext(InstanceContext): - """ """ + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> SupportingDocumentInstance: """ - Initialize the SupportingDocumentContext + Asynchronous coroutine to fetch the SupportingDocumentInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + :returns: The fetched SupportingDocumentInstance """ - super(SupportingDocumentContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/SupportingDocuments/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): + 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: """ - Fetch the SupportingDocumentInstance + Update the SupportingDocumentInstance - :returns: The fetched SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return SupportingDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + 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"] + ) - def update(self, friendly_name=values.unset, attributes=values.unset): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: """ - Update the SupportingDocumentInstance + Asynchronous coroutine to update the SupportingDocumentInstance - :param unicode friendly_name: The string that you assigned to describe the resource - :param dict attributes: The set of parameters that compose the Supporting Document resource + :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 - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance """ - data = values.of({'FriendlyName': friendly_name, 'Attributes': serialize.object(attributes), }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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" - return SupportingDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + 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 SupportingDocumentInstance(InstanceResource): - """ """ +class SupportingDocumentPage(Page): - class Status(object): - DRAFT = "draft" - PENDING_REVIEW = "pending-review" - REJECTED = "rejected" - APPROVED = "approved" - EXPIRED = "expired" - PROVISIONALLY_APPROVED = "provisionally-approved" + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: + """ + Build an instance of SupportingDocumentInstance - def __init__(self, version, payload, sid=None): + :param payload: Payload response from the API """ - Initialize the SupportingDocumentInstance + return SupportingDocumentInstance(self._version, payload) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + def __repr__(self) -> str: """ - super(SupportingDocumentInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'mime_type': payload.get('mime_type'), - 'status': payload.get('status'), - 'type': payload.get('type'), - 'attributes': payload.get('attributes'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 SupportingDocumentList(ListResource): - :returns: SupportingDocumentContext for this SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentContext + def __init__(self, version: Version): """ - if self._context is None: - self._context = SupportingDocumentContext(self._version, sid=self._solution['sid'], ) - return self._context + Initialize the SupportingDocumentList + + :param version: Version that contains the resource - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): + self._uri = "/RegulatoryCompliance/SupportingDocuments" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] - @property - def mime_type(self): + 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]: """ - :returns: The image type of the file - :rtype: unicode + 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 """ - return self._properties['mime_type'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def status(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentInstance]: """ - :returns: The verification status of the Supporting Document resource - :rtype: SupportingDocumentInstance.Status + 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 """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def type(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: """ - :returns: The type of the Supporting Document - :rtype: unicode + 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 self._properties['type'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def attributes(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: """ - :returns: The set of parameters that compose the Supporting Documents resource - :rtype: dict + 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: """ - return self._properties['attributes'] + Retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately - @property - def date_created(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 SupportingDocumentInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was 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 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: """ - return self._properties['date_created'] + Asynchronously retrieve a single page of SupportingDocumentInstance 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 SupportingDocumentInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 SupportingDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentPage: """ - return self._properties['date_updated'] + Retrieve a specific page of SupportingDocumentInstance 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 SupportingDocumentInstance """ - :returns: The absolute URL of the Supporting Document resource - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentPage: """ - return self._properties['url'] + Asynchronously retrieve a specific page of SupportingDocumentInstance 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 SupportingDocumentInstance """ - Fetch the SupportingDocumentInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentPage(self._version, response) - :returns: The fetched SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + def get(self, sid: str) -> SupportingDocumentContext: """ - return self._proxy.fetch() + Constructs a SupportingDocumentContext - def update(self, friendly_name=values.unset, attributes=values.unset): + :param sid: The unique string created by Twilio to identify the Supporting Document resource. """ - Update the SupportingDocumentInstance + return SupportingDocumentContext(self._version, sid=sid) - :param unicode friendly_name: The string that you assigned to describe the resource - :param dict attributes: The set of parameters that compose the Supporting Document resource + def __call__(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext - :returns: The updated SupportingDocumentInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document.SupportingDocumentInstance + :param sid: The unique string created by Twilio to identify the Supporting Document resource. """ - return self._proxy.update(friendly_name=friendly_name, attributes=attributes, ) + return SupportingDocumentContext(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/numbers/v2/regulatory_compliance/supporting_document_type.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py index b7a5971402..692248cb45 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -1,318 +1,410 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SupportingDocumentTypeList(ListResource): - """ """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "SupportingDocumentTypeContext": """ - Initialize the SupportingDocumentTypeList - - :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.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeList + :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance """ - super(SupportingDocumentTypeList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/RegulatoryCompliance/SupportingDocumentTypes'.format(**self._solution) + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the SupportingDocumentTypeInstance - :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.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance] + :returns: The fetched SupportingDocumentTypeInstance """ - 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) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance] + 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 SupportingDocumentTypeInstance 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 SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage +class SupportingDocumentTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the SupportingDocumentTypeContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + super().__init__(version) - return SupportingDocumentTypePage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes/{sid}".format( + **self._solution + ) - def get_page(self, target_url): + def fetch(self) -> SupportingDocumentTypeInstance: """ - Retrieve a specific page of SupportingDocumentTypeInstance records from the API. - Request is executed immediately + Fetch the SupportingDocumentTypeInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage + :returns: The fetched SupportingDocumentTypeInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return SupportingDocumentTypePage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a SupportingDocumentTypeContext + headers["Accept"] = "application/json" - :param sid: The unique string that identifies the Supporting Document Type resource + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - """ - return SupportingDocumentTypeContext(self._version, sid=sid, ) + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> SupportingDocumentTypeInstance: """ - Constructs a SupportingDocumentTypeContext + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance - :param sid: The unique string that identifies the Supporting Document Type resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext + :returns: The fetched SupportingDocumentTypeInstance """ - return SupportingDocumentTypeContext(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 SupportingDocumentTypePage(Page): - """ """ + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the SupportingDocumentTypePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypePage + :returns: Machine friendly representation """ - super(SupportingDocumentTypePage, 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 SupportingDocumentTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: """ Build an instance of SupportingDocumentTypeInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + :param payload: Payload response from the API """ - return SupportingDocumentTypeInstance(self._version, payload, ) + return SupportingDocumentTypeInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class SupportingDocumentTypeContext(InstanceContext): - """ """ +class SupportingDocumentTypeList(ListResource): - def __init__(self, version, sid): + def __init__(self, version: Version): """ - Initialize the SupportingDocumentTypeContext + Initialize the SupportingDocumentTypeList - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the Supporting Document Type resource + :param version: Version that contains the resource - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext """ - super(SupportingDocumentTypeContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/RegulatoryCompliance/SupportingDocumentTypes/{sid}'.format(**self._solution) + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: """ - Fetch the 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. - :returns: The fetched SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return SupportingDocumentTypeInstance(self._version, payload, sid=self._solution['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[SupportingDocumentTypeInstance]: """ - Provide a friendly representation + 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. - :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 SupportingDocumentTypeInstance(InstanceResource): - """ """ + 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. - def __init__(self, version, payload, sid=None): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Initialize the SupportingDocumentTypeInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: """ - super(SupportingDocumentTypeInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'machine_name': payload.get('machine_name'), - 'fields': payload.get('fields'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'sid': sid or self._properties['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 _proxy(self): + :returns: Page of SupportingDocumentTypeInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeContext - """ - if self._context is None: - self._context = SupportingDocumentTypeContext(self._version, sid=self._solution['sid'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def sid(self): - """ - :returns: The unique string that identifies the Supporting Document Type resource - :rtype: unicode - """ - return self._properties['sid'] + headers["Accept"] = "application/json" - @property - def friendly_name(self): + 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: """ - :returns: A human-readable description of the Supporting Document Type resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def machine_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 SupportingDocumentTypePage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: """ - :returns: The machine-readable description of the Supporting Document Type resource - :rtype: unicode + 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 """ - return self._properties['machine_name'] + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) - @property - def fields(self): + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: """ - :returns: The required information for creating a Supporting Document - :rtype: dict + 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 """ - return self._properties['fields'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentTypePage(self._version, response) - @property - def url(self): + def get(self, sid: str) -> SupportingDocumentTypeContext: """ - :returns: The absolute URL of the Supporting Document Type resource - :rtype: unicode + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. """ - return self._properties['url'] + return SupportingDocumentTypeContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> SupportingDocumentTypeContext: """ - Fetch the SupportingDocumentTypeInstance + Constructs a SupportingDocumentTypeContext - :returns: The fetched SupportingDocumentTypeInstance - :rtype: twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type.SupportingDocumentTypeInstance + :param sid: The unique string that identifies the Supporting Document Type resource. """ - return self._proxy.fetch() + return SupportingDocumentTypeContext(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/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 2172edfc0f..501ae417d0 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -1,256 +1,88 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.domain import Domain -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.sync import Sync -from twilio.rest.preview.trusted_comms import TrustedComms -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._sync = None - self._understand = None - self._wireless = None - self._trusted_comms = 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 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 trusted_comms(self): - """ - :returns: Version trusted_comms of preview - :rtype: twilio.rest.preview.trusted_comms.TrustedComms - """ - if self._trusted_comms is None: - self._trusted_comms = TrustedComms(self) - return self._trusted_comms - - @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 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 - - @property - def branded_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallList - """ - return self.trusted_comms.branded_calls - - @property - def brands_information(self): - """ - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationList - """ - return self.trusted_comms.brands_information - - @property - def businesses(self): - """ - :rtype: twilio.rest.preview.trusted_comms.business.BusinessList - """ - return self.trusted_comms.businesses - - @property - def cps(self): - """ - :rtype: twilio.rest.preview.trusted_comms.cps.CpsList - """ - return self.trusted_comms.cps - - @property - def current_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallList - """ - return self.trusted_comms.current_calls - - @property - def phone_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallList - """ - return self.trusted_comms.phone_calls - - 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 05229ba6a6..0000000000 --- a/twilio/rest/preview/bulk_exports/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -r""" -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 f960fef8f5..0000000000 --- a/twilio/rest/preview/bulk_exports/export/__init__.py +++ /dev/null @@ -1,299 +0,0 @@ -# coding=utf-8 -r""" -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 -from twilio.rest.preview.bulk_exports.export.export_custom_job import ExportCustomJobList -from twilio.rest.preview.bulk_exports.export.job import JobList - - -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 = {} - - # Components - self._jobs = None - - @property - def jobs(self): - """ - Access the jobs - - :returns: twilio.rest.preview.bulk_exports.export.job.JobList - :rtype: twilio.rest.preview.bulk_exports.export.job.JobList - """ - if self._jobs is None: - self._jobs = JobList(self._version, ) - return self._jobs - - def get(self, resource_type): - """ - Constructs a ExportContext - - :param resource_type: The type of communication – Messages, Calls - - :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 type of communication – Messages, Calls - - :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 type of communication – Messages, Calls - - :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 - self._export_custom_jobs = None - - def fetch(self): - """ - Fetch the ExportInstance - - :returns: The fetched ExportInstance - :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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 - - @property - def export_custom_jobs(self): - """ - Access the export_custom_jobs - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - """ - if self._export_custom_jobs is None: - self._export_custom_jobs = ExportCustomJobList( - self._version, - resource_type=self._solution['resource_type'], - ) - return self._export_custom_jobs - - 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.get('resource_type'), - 'url': payload.get('url'), - 'links': payload.get('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 type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - - @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 the ExportInstance - - :returns: The 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 - - @property - def export_custom_jobs(self): - """ - Access the export_custom_jobs - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - """ - return self._proxy.export_custom_jobs - - 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 09808071b8..0000000000 --- a/twilio/rest/preview/bulk_exports/export/day.py +++ /dev/null @@ -1,372 +0,0 @@ -# coding=utf-8 -r""" -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 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 type of communication – Messages, Calls - - :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, next_token=values.unset, previous_token=values.unset, - 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 unicode next_token: The next_token - :param unicode previous_token: The previous_token - :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( - next_token=next_token, - previous_token=previous_token, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit']) - - def list(self, next_token=values.unset, previous_token=values.unset, 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 unicode next_token: The next_token - :param unicode previous_token: The previous_token - :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( - next_token=next_token, - previous_token=previous_token, - limit=limit, - page_size=page_size, - )) - - def page(self, next_token=values.unset, previous_token=values.unset, - 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 unicode next_token: The next_token - :param unicode previous_token: The previous_token - :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 - """ - data = values.of({ - 'NextToken': next_token, - 'PreviousToken': previous_token, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 get(self, day): - """ - Constructs a DayContext - - :param day: The date of the data in the file - - :returns: twilio.rest.preview.bulk_exports.export.day.DayContext - :rtype: twilio.rest.preview.bulk_exports.export.day.DayContext - """ - return DayContext(self._version, resource_type=self._solution['resource_type'], day=day, ) - - def __call__(self, day): - """ - Constructs a DayContext - - :param day: The date of the data in the file - - :returns: twilio.rest.preview.bulk_exports.export.day.DayContext - :rtype: twilio.rest.preview.bulk_exports.export.day.DayContext - """ - return DayContext(self._version, resource_type=self._solution['resource_type'], day=day, ) - - 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 type of communication – Messages, Calls - - :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 DayContext(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, day): - """ - Initialize the DayContext - - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls - :param day: The date of the data in the file - - :returns: twilio.rest.preview.bulk_exports.export.day.DayContext - :rtype: twilio.rest.preview.bulk_exports.export.day.DayContext - """ - super(DayContext, self).__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): - """ - Fetch the DayInstance - - :returns: The fetched DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DayInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - day=self._solution['day'], - ) - - 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 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, day=None): - """ - 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')), - 'create_date': payload.get('create_date'), - 'friendly_name': payload.get('friendly_name'), - 'resource_type': payload.get('resource_type'), - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type, 'day': day or self._properties['day'], } - - @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: DayContext for this DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayContext - """ - if self._context is None: - self._context = DayContext( - self._version, - resource_type=self._solution['resource_type'], - day=self._solution['day'], - ) - return self._context - - @property - def redirect_to(self): - """ - :returns: The redirect_to - :rtype: unicode - """ - return self._properties['redirect_to'] - - @property - def day(self): - """ - :returns: The date of the data in the file - :rtype: unicode - """ - return self._properties['day'] - - @property - def size(self): - """ - :returns: Size of the file in bytes - :rtype: unicode - """ - return self._properties['size'] - - @property - def create_date(self): - """ - :returns: The date when resource is created - :rtype: unicode - """ - return self._properties['create_date'] - - @property - def friendly_name(self): - """ - :returns: The friendly name specified when creating the job - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - - def fetch(self): - """ - Fetch the DayInstance - - :returns: The fetched DayInstance - :rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance - """ - 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/bulk_exports/export/export_custom_job.py b/twilio/rest/preview/bulk_exports/export/export_custom_job.py deleted file mode 100644 index a8c259cc9b..0000000000 --- a/twilio/rest/preview/bulk_exports/export/export_custom_job.py +++ /dev/null @@ -1,336 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 ExportCustomJobList(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 ExportCustomJobList - - :param Version version: Version that contains the resource - :param resource_type: The type of communication – Messages, Calls - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobList - """ - super(ExportCustomJobList, self).__init__(version) - - # Path Solution - self._solution = {'resource_type': resource_type, } - self._uri = '/Exports/{resource_type}/Jobs'.format(**self._solution) - - def stream(self, next_token=values.unset, previous_token=values.unset, - limit=None, page_size=None): - """ - 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 unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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.export_custom_job.ExportCustomJobInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - next_token=next_token, - previous_token=previous_token, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit']) - - def list(self, next_token=values.unset, previous_token=values.unset, limit=None, - page_size=None): - """ - 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 unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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.export_custom_job.ExportCustomJobInstance] - """ - return list(self.stream( - next_token=next_token, - previous_token=previous_token, - limit=limit, - page_size=page_size, - )) - - def page(self, next_token=values.unset, previous_token=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of ExportCustomJobInstance records from the API. - Request is executed immediately - - :param unicode next_token: The token for the next page of job results - :param unicode previous_token: The token for the previous page of result - :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 ExportCustomJobInstance - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobPage - """ - data = values.of({ - 'NextToken': next_token, - 'PreviousToken': previous_token, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ExportCustomJobPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ExportCustomJobInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ExportCustomJobInstance - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ExportCustomJobPage(self._version, response, self._solution) - - def create(self, friendly_name=values.unset, start_day=values.unset, - end_day=values.unset, webhook_url=values.unset, - webhook_method=values.unset, email=values.unset): - """ - Create the ExportCustomJobInstance - - :param unicode friendly_name: The friendly_name - :param unicode start_day: The start_day - :param unicode end_day: The end_day - :param unicode webhook_url: The webhook_url - :param unicode webhook_method: The webhook_method - :param unicode email: The email - - :returns: The created ExportCustomJobInstance - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'StartDay': start_day, - 'EndDay': end_day, - 'WebhookUrl': webhook_url, - 'WebhookMethod': webhook_method, - 'Email': email, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ExportCustomJobInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportCustomJobPage(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 ExportCustomJobPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param resource_type: The type of communication – Messages, Calls - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobPage - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobPage - """ - super(ExportCustomJobPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExportCustomJobInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobInstance - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobInstance - """ - return ExportCustomJobInstance( - self._version, - payload, - resource_type=self._solution['resource_type'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ExportCustomJobInstance(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 ExportCustomJobInstance - - :returns: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobInstance - :rtype: twilio.rest.preview.bulk_exports.export.export_custom_job.ExportCustomJobInstance - """ - super(ExportCustomJobInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'friendly_name': payload.get('friendly_name'), - 'resource_type': payload.get('resource_type'), - 'start_day': payload.get('start_day'), - 'end_day': payload.get('end_day'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'email': payload.get('email'), - 'job_sid': payload.get('job_sid'), - 'details': payload.get('details'), - } - - # Context - self._context = None - self._solution = {'resource_type': resource_type, } - - @property - def friendly_name(self): - """ - :returns: The friendly name specified when creating the job - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - - @property - def start_day(self): - """ - :returns: The start time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['start_day'] - - @property - def end_day(self): - """ - :returns: The end time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['end_day'] - - @property - def webhook_url(self): - """ - :returns: The optional webhook url called on completion - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def webhook_method(self): - """ - :returns: This is the method used to call the webhook - :rtype: unicode - """ - return self._properties['webhook_method'] - - @property - def email(self): - """ - :returns: The optional email to send the completion notification to - :rtype: unicode - """ - return self._properties['email'] - - @property - def job_sid(self): - """ - :returns: The job_sid returned when the export was created - :rtype: unicode - """ - return self._properties['job_sid'] - - @property - def details(self): - """ - :returns: The details - :rtype: dict - """ - return self._properties['details'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/bulk_exports/export/job.py b/twilio/rest/preview/bulk_exports/export/job.py deleted file mode 100644 index 2bcde140ae..0000000000 --- a/twilio/rest/preview/bulk_exports/export/job.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding=utf-8 -r""" -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 JobList(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 JobList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.bulk_exports.export.job.JobList - :rtype: twilio.rest.preview.bulk_exports.export.job.JobList - """ - super(JobList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, job_sid): - """ - Constructs a JobContext - - :param job_sid: The job_sid - - :returns: twilio.rest.preview.bulk_exports.export.job.JobContext - :rtype: twilio.rest.preview.bulk_exports.export.job.JobContext - """ - return JobContext(self._version, job_sid=job_sid, ) - - def __call__(self, job_sid): - """ - Constructs a JobContext - - :param job_sid: The job_sid - - :returns: twilio.rest.preview.bulk_exports.export.job.JobContext - :rtype: twilio.rest.preview.bulk_exports.export.job.JobContext - """ - return JobContext(self._version, job_sid=job_sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class JobPage(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 JobPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.bulk_exports.export.job.JobPage - :rtype: twilio.rest.preview.bulk_exports.export.job.JobPage - """ - super(JobPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of JobInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.bulk_exports.export.job.JobInstance - :rtype: twilio.rest.preview.bulk_exports.export.job.JobInstance - """ - return JobInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class JobContext(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, job_sid): - """ - Initialize the JobContext - - :param Version version: Version that contains the resource - :param job_sid: The job_sid - - :returns: twilio.rest.preview.bulk_exports.export.job.JobContext - :rtype: twilio.rest.preview.bulk_exports.export.job.JobContext - """ - super(JobContext, self).__init__(version) - - # Path Solution - self._solution = {'job_sid': job_sid, } - self._uri = '/Exports/Jobs/{job_sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the JobInstance - - :returns: The fetched JobInstance - :rtype: twilio.rest.preview.bulk_exports.export.job.JobInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return JobInstance(self._version, payload, job_sid=self._solution['job_sid'], ) - - def delete(self): - """ - Deletes the JobInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 JobInstance(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, job_sid=None): - """ - Initialize the JobInstance - - :returns: twilio.rest.preview.bulk_exports.export.job.JobInstance - :rtype: twilio.rest.preview.bulk_exports.export.job.JobInstance - """ - super(JobInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'resource_type': payload.get('resource_type'), - 'friendly_name': payload.get('friendly_name'), - 'details': payload.get('details'), - 'start_day': payload.get('start_day'), - 'end_day': payload.get('end_day'), - 'job_sid': payload.get('job_sid'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'email': payload.get('email'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'job_sid': job_sid or self._properties['job_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: JobContext for this JobInstance - :rtype: twilio.rest.preview.bulk_exports.export.job.JobContext - """ - if self._context is None: - self._context = JobContext(self._version, job_sid=self._solution['job_sid'], ) - return self._context - - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - - @property - def friendly_name(self): - """ - :returns: The friendly name specified when creating the job - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def details(self): - """ - :returns: This is a list of the completed, pending, or errored dates within the export time range, with one entry for each status with more than one day in that status - :rtype: dict - """ - return self._properties['details'] - - @property - def start_day(self): - """ - :returns: The start time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['start_day'] - - @property - def end_day(self): - """ - :returns: The end time for the export specified when creating the job - :rtype: unicode - """ - return self._properties['end_day'] - - @property - def job_sid(self): - """ - :returns: The job_sid returned when the export was created - :rtype: unicode - """ - return self._properties['job_sid'] - - @property - def webhook_url(self): - """ - :returns: The optional webhook url called on completion - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def webhook_method(self): - """ - :returns: This is the method used to call the webhook - :rtype: unicode - """ - return self._properties['webhook_method'] - - @property - def email(self): - """ - :returns: The optional email to send the completion notification to - :rtype: unicode - """ - return self._properties['email'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the JobInstance - - :returns: The fetched JobInstance - :rtype: twilio.rest.preview.bulk_exports.export.job.JobInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the JobInstance - - :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/bulk_exports/export_configuration.py b/twilio/rest/preview/bulk_exports/export_configuration.py deleted file mode 100644 index 5efaf43904..0000000000 --- a/twilio/rest/preview/bulk_exports/export_configuration.py +++ /dev/null @@ -1,291 +0,0 @@ -# coding=utf-8 -r""" -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 type of communication – Messages, Calls - - :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 type of communication – Messages, Calls - - :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 type of communication – Messages, Calls - - :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 the ExportConfigurationInstance - - :returns: The fetched ExportConfigurationInstance - :rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: Whether files are automatically generated - :param unicode webhook_url: URL targeted at export - :param unicode webhook_method: Whether to GET or POST to the webhook url - - :returns: The 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(method='POST', uri=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.get('enabled'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'resource_type': payload.get('resource_type'), - 'url': payload.get('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: Whether files are automatically generated - :rtype: bool - """ - return self._properties['enabled'] - - @property - def webhook_url(self): - """ - :returns: URL targeted at export - :rtype: unicode - """ - return self._properties['webhook_url'] - - @property - def webhook_method(self): - """ - :returns: Whether to GET or POST to the webhook url - :rtype: unicode - """ - return self._properties['webhook_method'] - - @property - def resource_type(self): - """ - :returns: The type of communication – Messages, Calls - :rtype: unicode - """ - return self._properties['resource_type'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the ExportConfigurationInstance - - :returns: The 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: Whether files are automatically generated - :param unicode webhook_url: URL targeted at export - :param unicode webhook_method: Whether to GET or POST to the webhook url - - :returns: The 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 1bb97fcce3..0000000000 --- a/twilio/rest/preview/deployed_devices/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -r""" -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 ae5c09614f..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,527 +0,0 @@ -# coding=utf-8 -r""" -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 the FleetInstance - - :param unicode friendly_name: A human readable description for this Fleet. - - :returns: The created FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the FleetInstance - - :returns: The fetched FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The updated FleetInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.FleetInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DefaultDeploymentSid': default_deployment_sid, }) - - payload = self._version.update(method='POST', uri=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.get('sid'), - 'url': payload.get('url'), - 'unique_name': payload.get('unique_name'), - 'friendly_name': payload.get('friendly_name'), - 'account_sid': payload.get('account_sid'), - 'default_deployment_sid': payload.get('default_deployment_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'links': payload.get('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 the FleetInstance - - :returns: The 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: The 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 9f376979fa..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/certificate.py +++ /dev/null @@ -1,456 +0,0 @@ -# coding=utf-8 -r""" -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 the 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: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({ - 'DeviceSid': device_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the CertificateInstance - - :returns: The fetched CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The updated CertificateInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.update(method='POST', uri=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.get('sid'), - 'url': payload.get('url'), - 'friendly_name': payload.get('friendly_name'), - 'fleet_sid': payload.get('fleet_sid'), - 'account_sid': payload.get('account_sid'), - 'device_sid': payload.get('device_sid'), - 'thumbprint': payload.get('thumbprint'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('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 the CertificateInstance - - :returns: The 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: The 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 a9010d1097..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/deployment.py +++ /dev/null @@ -1,433 +0,0 @@ -# coding=utf-8 -r""" -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 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: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the DeploymentInstance - - :returns: The fetched DeploymentInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.deployment.DeploymentInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('sid'), - 'url': payload.get('url'), - 'friendly_name': payload.get('friendly_name'), - 'fleet_sid': payload.get('fleet_sid'), - 'account_sid': payload.get('account_sid'), - 'sync_service_sid': payload.get('sync_service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('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 the DeploymentInstance - - :returns: The 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: The 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 d72d0b2cac..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/device.py +++ /dev/null @@ -1,504 +0,0 @@ -# coding=utf-8 -r""" -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 the 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: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({ - 'DeploymentSid': deployment_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the DeviceInstance - - :returns: The fetched DeviceInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('sid'), - 'url': payload.get('url'), - 'unique_name': payload.get('unique_name'), - 'friendly_name': payload.get('friendly_name'), - 'fleet_sid': payload.get('fleet_sid'), - 'enabled': payload.get('enabled'), - 'account_sid': payload.get('account_sid'), - 'identity': payload.get('identity'), - 'deployment_sid': payload.get('deployment_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'date_authenticated': deserialize.iso8601_datetime(payload.get('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 the DeviceInstance - - :returns: The 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: The 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 4e989d64b7..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/key.py +++ /dev/null @@ -1,450 +0,0 @@ -# coding=utf-8 -r""" -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 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: The created KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.create(method='POST', uri=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']) - - 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 - """ - data = values.of({ - 'DeviceSid': device_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the KeyInstance - - :returns: The fetched KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The updated KeyInstance - :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyInstance - """ - data = values.of({'FriendlyName': friendly_name, 'DeviceSid': device_sid, }) - - payload = self._version.update(method='POST', uri=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.get('sid'), - 'url': payload.get('url'), - 'friendly_name': payload.get('friendly_name'), - 'fleet_sid': payload.get('fleet_sid'), - 'account_sid': payload.get('account_sid'), - 'device_sid': payload.get('device_sid'), - 'secret': payload.get('secret'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('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 the KeyInstance - - :returns: The 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: The 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 74eaa01930..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 2649ecafb5..49d3d40da5 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -1,502 +1,755 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + 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 """ - data = values.of({ - 'Email': email, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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) + 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. - def create(self, hosted_number_order_sids, address_sid, email, contact_title, - contact_phone_number, cc_emails=values.unset): + :returns: The updated AuthorizationDocumentInstance """ - Create 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 contact_title: Title of signee of this Authorization Document. - :param unicode contact_phone_number: Authorization Document's signee's phone number. - :param unicode cc_emails: A list of emails. + 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, + ) - :returns: The created AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ - 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), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AuthorizationDocumentInstance(self._version, payload, ) - - def get(self, sid): + Access the dependent_hosted_number_orders """ - Constructs a AuthorizationDocumentContext - - :param sid: AuthorizationDocument sid. + return self._proxy.dependent_hosted_number_orders - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentContext + def __repr__(self) -> str: """ - return AuthorizationDocumentContext(self._version, sid=sid, ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a AuthorizationDocumentContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - :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, ) +class AuthorizationDocumentContext(InstanceContext): - def __repr__(self): + def __init__(self, version: Version, sid: str): """ - Provide a friendly representation + Initialize the AuthorizationDocumentContext - :returns: Machine friendly representation - :rtype: str + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ - return '' + super().__init__(version) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AuthorizationDocuments/{sid}".format(**self._solution) -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. """ + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None - def __init__(self, version, response, solution): + def fetch(self) -> AuthorizationDocumentInstance: """ - Initialize the AuthorizationDocumentPage + Fetch the AuthorizationDocumentInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage + :returns: The fetched AuthorizationDocumentInstance """ - super(AuthorizationDocumentPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of AuthorizationDocumentInstance + 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.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - """ - return AuthorizationDocumentInstance(self._version, payload, ) + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> AuthorizationDocumentInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the AuthorizationDocumentInstance - :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 = await self._version.fetch_async( + 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 + 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: """ - super(AuthorizationDocumentContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/AuthorizationDocuments/{sid}'.format(**self._solution) + Update the AuthorizationDocumentInstance - # Dependents - self._dependent_hosted_number_orders = None + :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. - def fetch(self): + :returns: The updated AuthorizationDocumentInstance """ - Fetch the AuthorizationDocumentInstance - :returns: The fetched AuthorizationDocumentInstance - :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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({}) - return AuthorizationDocumentInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def update(self, hosted_number_order_sids=values.unset, - address_sid=values.unset, email=values.unset, cc_emails=values.unset, - status=values.unset, contact_title=values.unset, - contact_phone_number=values.unset): - """ - Update the AuthorizationDocumentInstance + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) - :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 unicode contact_title: Title of signee of this Authorization Document. - :param unicode contact_phone_number: Authorization Document's signee's phone number. + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. :returns: The updated AuthorizationDocumentInstance - :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, - 'ContactTitle': contact_title, - 'ContactPhoneNumber': contact_phone_number, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], ) + 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.get('sid'), - 'address_sid': payload.get('address_sid'), - 'status': payload.get('status'), - 'email': payload.get('email'), - 'cc_emails': payload.get('cc_emails'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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): + self._uri = "/AuthorizationDocuments" + + def create( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: """ - :returns: The Status of this AuthorizationDocument. - :rtype: AuthorizationDocumentInstance.Status + 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['status'] - @property - def email(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: """ - :returns: Email. - :rtype: unicode + 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 """ - 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 = 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 the AuthorizationDocumentInstance + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) - :returns: The 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, contact_title=values.unset, - contact_phone_number=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. - :param unicode contact_title: Title of signee of this Authorization Document. - :param unicode contact_phone_number: Authorization Document's signee's phone number. + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext - :returns: The 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, - contact_title=contact_title, - contact_phone_number=contact_phone_number, - ) + 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 6701cae222..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,457 +1,477 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) - - 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 - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.verification_type: Optional[ + "DependentHostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" ) - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'incoming_phone_number_sid': payload.get('incoming_phone_number_sid'), - 'address_sid': payload.get('address_sid'), - 'signing_document_sid': payload.get('signing_document_sid'), - 'phone_number': payload.get('phone_number'), - 'capabilities': payload.get('capabilities'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'status': payload.get('status'), - 'failure_reason': payload.get('failure_reason'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'verification_attempts': deserialize.integer(payload.get('verification_attempts')), - 'email': payload.get('email'), - 'cc_emails': payload.get('cc_emails'), - 'verification_type': payload.get('verification_type'), - 'verification_document_sid': payload.get('verification_document_sid'), - 'extension': payload.get('extension'), - 'call_delay': deserialize.integer(payload.get('call_delay')), - 'verification_code': payload.get('verification_code'), - 'verification_call_sids': payload.get('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): + :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: """ - :returns: The Status of this HostedNumberOrder. - :rtype: DependentHostedNumberOrderInstance.Status - """ - 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 da3559e775..0c20af8791 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -1,699 +1,985 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + 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 + Asynchronous coroutine that 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 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 + :returns: True if delete succeeds, False otherwise """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.delete_async() - return HostedNumberOrderPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "HostedNumberOrderInstance": """ - Retrieve a specific page of HostedNumberOrderInstance records from the API. - Request is executed immediately + Fetch the HostedNumberOrderInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderPage + :returns: The fetched HostedNumberOrderInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return HostedNumberOrderPage(self._version, response, self._solution) + return self._proxy.fetch() - 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): + async def fetch_async(self) -> "HostedNumberOrderInstance": """ - Create the HostedNumberOrderInstance + Asynchronous coroutine to fetch the 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: The 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return HostedNumberOrderInstance(self._version, payload, ) - - def get(self, sid): + :returns: The fetched HostedNumberOrderInstance """ - Constructs a HostedNumberOrderContext - - :param sid: HostedNumberOrder sid. - - :returns: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderContext + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": """ - return HostedNumberOrderContext(self._version, sid=sid, ) + Update the HostedNumberOrderInstance - def __call__(self, 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: The updated HostedNumberOrderInstance """ - Constructs a HostedNumberOrderContext + 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, + ) - :param sid: HostedNumberOrder sid. + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. - :returns: 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 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): + 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({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: """ - Fetch the HostedNumberOrderInstance + Asynchronous coroutine to fetch the HostedNumberOrderInstance + :returns: The fetched HostedNumberOrderInstance - :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return HostedNumberOrderInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the HostedNumberOrderInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=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): + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: """ Update the HostedNumberOrderInstance - :param 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: Digits to dial after connecting the verification call. - :param unicode call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return HostedNumberOrderInstance(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.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) -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. """ + 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. - 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: The updated HostedNumberOrderInstance + """ - class VerificationType(object): - PHONE_CALL = "phone-call" - PHONE_BILL = "phone-bill" + 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({}) - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'incoming_phone_number_sid': payload.get('incoming_phone_number_sid'), - 'address_sid': payload.get('address_sid'), - 'signing_document_sid': payload.get('signing_document_sid'), - 'phone_number': payload.get('phone_number'), - 'capabilities': payload.get('capabilities'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'status': payload.get('status'), - 'failure_reason': payload.get('failure_reason'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'verification_attempts': deserialize.integer(payload.get('verification_attempts')), - 'email': payload.get('email'), - 'cc_emails': payload.get('cc_emails'), - 'url': payload.get('url'), - 'verification_type': payload.get('verification_type'), - 'verification_document_sid': payload.get('verification_document_sid'), - 'extension': payload.get('extension'), - 'call_delay': deserialize.integer(payload.get('call_delay')), - 'verification_code': payload.get('verification_code'), - 'verification_call_sids': payload.get('verification_call_sids'), - } + 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.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :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 + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) - @property - def sid(self): - """ - :returns: HostedNumberOrder sid. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: 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 incoming_phone_number_sid(self): - """ - :returns: IncomingPhoneNumber sid. - :rtype: unicode - """ - return self._properties['incoming_phone_number_sid'] - @property - def address_sid(self): - """ - :returns: Address sid. - :rtype: unicode - """ - return self._properties['address_sid'] +class HostedNumberOrderPage(Page): - @property - def signing_document_sid(self): - """ - :returns: LOA document sid. - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: """ - return self._properties['signing_document_sid'] + Build an instance of HostedNumberOrderInstance - @property - def phone_number(self): - """ - :returns: An E164 formatted phone number. - :rtype: unicode + :param payload: Payload response from the API """ - return self._properties['phone_number'] + return HostedNumberOrderInstance(self._version, payload) - @property - def capabilities(self): - """ - :returns: A mapping of phone number capabilities. - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['capabilities'] + Provide a friendly representation - @property - def friendly_name(self): - """ - :returns: A human readable description of this resource. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['friendly_name'] + return "" - @property - def unique_name(self): - """ - :returns: A unique, developer assigned name of this HostedNumberOrder. - :rtype: unicode - """ - return self._properties['unique_name'] - @property - def status(self): - """ - :returns: The Status of this HostedNumberOrder. - :rtype: HostedNumberOrderInstance.Status - """ - return self._properties['status'] +class HostedNumberOrderList(ListResource): - @property - def failure_reason(self): - """ - :returns: Why a hosted_number_order reached status "action-required" - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['failure_reason'] + Initialize the HostedNumberOrderList - @property - def date_created(self): - """ - :returns: The date this HostedNumberOrder was created. - :rtype: datetime + :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: """ - return self._properties['date_created'] + Create the HostedNumberOrderInstance - @property - def date_updated(self): - """ - :returns: The date this HostedNumberOrder was updated. - :rtype: datetime - """ - return self._properties['date_updated'] + :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. - @property - def verification_attempts(self): - """ - :returns: The number of attempts made to verify ownership of the phone number. - :rtype: unicode + :returns: The created HostedNumberOrderInstance """ - return self._properties['verification_attempts'] - @property - def email(self): - """ - :returns: Email. - :rtype: unicode - """ - return self._properties['email'] + 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 cc_emails(self): - """ - :returns: A list of emails. - :rtype: unicode - """ - return self._properties['cc_emails'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def url(self): - """ - :returns: The URL of this HostedNumberOrder. - :rtype: unicode - """ - return self._properties['url'] + headers["Accept"] = "application/json" - @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'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def verification_document_sid(self): + 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 """ - :returns: Verification Document Sid. - :rtype: unicode + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + def stream( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HostedNumberOrderInstance]: """ - 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 the HostedNumberOrderInstance + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) - :returns: The 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: Digits to dial after connecting the verification call. - :param unicode call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext - :returns: The 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 bcf31a09a1..fcc99a4112 100644 --- a/twilio/rest/preview/marketplace/__init__.py +++ b/twilio/rest/preview/marketplace/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 17c54971d6..e81ec649de 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -1,373 +1,438 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) - 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. """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + super().__init__(version) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + # 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 SID of the AvailableAddOn resource to fetch + 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 SID of the AvailableAddOn resource to fetch - :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 SID of the AvailableAddOn resource to fetch + :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. - def fetch(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 """ - Fetch the AvailableAddOnInstance + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - :returns: The fetched AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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. - return AvailableAddOnInstance(self._version, payload, 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) - @property - def extensions(self): + :returns: Generator that will yield up to limit results """ - Access the extensions + limits = self._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.AvailableAddOnExtensionList - :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionList + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: """ - if self._extensions is None: - self._extensions = AvailableAddOnExtensionList( - self._version, - available_add_on_sid=self._solution['sid'], - ) - return self._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. - 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 """ - Provide a friendly representation + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: Machine friendly representation - :rtype: str + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -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. """ + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def __init__(self, version, payload, sid=None): + 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: """ - Initialize the AvailableAddOnInstance + 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: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnInstance + :returns: Page of AvailableAddOnInstance """ - super(AvailableAddOnInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'description': payload.get('description'), - 'pricing_type': payload.get('pricing_type'), - 'configuration_schema': payload.get('configuration_schema'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + headers = values.of({"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 + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) - :returns: AvailableAddOnContext for this AvailableAddOnInstance - :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnContext + async def 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: """ - if self._context is None: - self._context = AvailableAddOnContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['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 string that you assigned to describe the resource - :rtype: unicode + :returns: Page of AvailableAddOnInstance """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def description(self): - """ - :returns: A short description of the Add-on's functionality - :rtype: unicode - """ - return self._properties['description'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def pricing_type(self): - """ - :returns: How customers are charged for using this Add-on - :rtype: unicode - """ - return self._properties['pricing_type'] + headers["Accept"] = "application/json" - @property - def configuration_schema(self): - """ - :returns: The JSON object with the configuration that must be provided when installing a given Add-on - :rtype: dict - """ - return self._properties['configuration_schema'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) - @property - def url(self): + def get_page(self, target_url: str) -> AvailableAddOnPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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['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 URLs of related resources - :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 the AvailableAddOnInstance + Constructs a AvailableAddOnContext - :returns: The 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 ef5dfc9625..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,362 +1,445 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the AvailableAddOn resource to which this extension applies + 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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AvailableAddOnExtensionContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 SID of the AvailableAddOn Extension resource to fetch + 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 SID of the AvailableAddOn Extension resource to fetch - :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 SID of the AvailableAddOn resource to which this extension applies - - :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 SID of the AvailableAddOn resource with the extension to fetch - :param sid: The SID of the AvailableAddOn Extension resource to fetch + :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 the AvailableAddOnExtensionInstance + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) - :returns: The 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]: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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"]) - :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 + return self._version.stream_async(page, limits["limit"]) + + 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.get('sid'), - 'available_add_on_sid': payload.get('available_add_on_sid'), - 'friendly_name': payload.get('friendly_name'), - 'product_name': payload.get('product_name'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('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): + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - 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 SID of the AvailableAddOn resource to which this extension applies - :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: The string that you assigned to describe the resource - :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: The name 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: An application-defined string that uniquely identifies the resource - :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 absolute URL of the resource - :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 the AvailableAddOnExtensionInstance + Constructs a AvailableAddOnExtensionContext - :returns: The 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 2d92f73620..7f1fadc510 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -1,472 +1,671 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 the InstalledAddOnInstance - - :param unicode available_add_on_sid: The SID of the AvaliableAddOn to install - :param bool accept_terms_of_service: Whether the Terms of Service were accepted - :param dict configuration: The JSON object representing the configuration - :param unicode unique_name: An application-defined string that uniquely identifies the resource + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The 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(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - 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 SID of the InstalledAddOn resource to fetch + :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 SID of the InstalledAddOn resource to fetch - - :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) + + self._extensions: Optional[InstalledAddOnExtensionList] = None - def get_instance(self, payload): + 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 SID of the InstalledAddOn resource to fetch - :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(method='DELETE', uri=self._uri, ) + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> InstalledAddOnInstance: """ - Fetch the InstalledAddOnInstance + Asynchronous coroutine to fetch the InstalledAddOnInstance + :returns: The fetched InstalledAddOnInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return InstalledAddOnInstance(self._version, payload, sid=self._solution['sid'], ) + 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=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: An application-defined string that uniquely identifies the resource + :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 - :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance """ - data = values.of({'Configuration': serialize.object(configuration), 'UniqueName': unique_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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 - return InstalledAddOnInstance(self._version, payload, sid=self._solution['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: 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'description': payload.get('description'), - 'configuration': payload.get('configuration'), - 'unique_name': payload.get('unique_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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): + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): + :returns: Machine friendly representation """ - :returns: The SID of the Account that created the resource - :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: The string that you assigned to describe the resource - :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's 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 that represents the current configuration of installed Add-on - :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: An application-defined string that uniquely identifies the resource - :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 ISO 8601 date and time in GMT when the resource 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 ISO 8601 date and time in GMT when the resource 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 absolute URL of the resource - :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 URLs of related resources - :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 + + :param page_token: PageToken provided by the 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 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of InstalledAddOnInstance """ - Fetch the InstalledAddOnInstance + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) - :returns: The 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: An application-defined string that uniquely identifies the resource + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext - :returns: The 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 e5b776ab4d..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,402 +1,533 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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. """ - - def __init__(self, version, installed_add_on_sid): - """ - Initialize the InstalledAddOnExtensionList +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") - :param Version version: Version that contains the resource - :param installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnExtensionContext] = None - :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 + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": """ - super(InstalledAddOnExtensionList, self).__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) + 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: InstalledAddOnExtensionContext for this 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) + 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance] + def fetch(self) -> "InstalledAddOnExtensionInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the InstalledAddOnExtensionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch 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) - :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 fetched InstalledAddOnExtensionInstance """ - 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, enabled: bool) -> "InstalledAddOnExtensionInstance": """ - Retrieve a single page of InstalledAddOnExtensionInstance records from the API. - Request is executed immediately + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + enabled=enabled, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance - return InstalledAddOnExtensionPage(self._version, response, self._solution) + :param enabled: Whether the Extension should be invoked. - def get_page(self, target_url): + :returns: The updated InstalledAddOnExtensionInstance """ - Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. - Request is executed immediately + return await self._proxy.update_async( + enabled=enabled, + ) - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + 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 SID of the InstalledAddOn Extension resource to fetch + 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 SID of the InstalledAddOn Extension resource to fetch - :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 SID of the InstalledAddOn resource to which this extension applies - :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 SID of the InstalledAddOn resource with the extension to fetch - :param sid: The SID of the InstalledAddOn Extension resource to fetch + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - :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 + 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: """ - 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 the InstalledAddOnExtensionInstance - :returns: The fetched InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + 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: Whether the Extension should be invoked + Provide a friendly representation - :returns: The updated InstalledAddOnExtensionInstance - :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance + :returns: Machine friendly representation """ - data = values.of({'Enabled': enabled, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + - payload = self._version.update(method='POST', uri=self._uri, data=data, ) +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.get('sid'), - 'installed_add_on_sid': payload.get('installed_add_on_sid'), - 'friendly_name': payload.get('friendly_name'), - 'product_name': payload.get('product_name'), - 'unique_name': payload.get('unique_name'), - 'enabled': payload.get('enabled'), - 'url': payload.get('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: The unique string that identifies the resource - :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 SID of the InstalledAddOn resource to which this extension 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[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: The string that you assigned to describe the 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[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: The name 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: An application-defined string that uniquely identifies the 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 = 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: Whether 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 absolute URL of the resource - :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 the InstalledAddOnExtensionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) - :returns: The 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: Whether the Extension should be invoked + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext - :returns: The 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/sync/__init__.py b/twilio/rest/preview/sync/__init__.py deleted file mode 100644 index 6a56a99bb6..0000000000 --- a/twilio/rest/preview/sync/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -r""" -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 b96080453d..0000000000 --- a/twilio/rest/preview/sync/service/__init__.py +++ /dev/null @@ -1,535 +0,0 @@ -# coding=utf-8 -r""" -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 the 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: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the ServiceInstance - - :returns: The fetched ServiceInstance - :rtype: twilio.rest.preview.sync.service.ServiceInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'webhook_url': payload.get('webhook_url'), - 'reachability_webhooks_enabled': payload.get('reachability_webhooks_enabled'), - 'acl_enabled': payload.get('acl_enabled'), - 'links': payload.get('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 the ServiceInstance - - :returns: The 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: The 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 731e9d1568..0000000000 --- a/twilio/rest/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,498 +0,0 @@ -# coding=utf-8 -r""" -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 the DocumentInstance - - :param unicode unique_name: The unique_name - :param dict data: The data - - :returns: The created DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - data = values.of({'UniqueName': unique_name, 'Data': serialize.object(data), }) - - payload = self._version.create(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the DocumentInstance - - :returns: The fetched DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self, if_match=values.unset): - """ - Deletes the DocumentInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'If-Match': if_match, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def update(self, data, if_match=values.unset): - """ - Update the DocumentInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - data = values.of({'Data': serialize.object(data), }) - headers = values.of({'If-Match': if_match, }) - - 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'], - ) - - @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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 the DocumentInstance - - :returns: The fetched DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - return self._proxy.fetch() - - def delete(self, if_match=values.unset): - """ - Deletes the DocumentInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(if_match=if_match, ) - - def update(self, data, if_match=values.unset): - """ - Update the DocumentInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - :rtype: twilio.rest.preview.sync.service.document.DocumentInstance - """ - return self._proxy.update(data, if_match=if_match, ) - - @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 d1c67730f2..0000000000 --- a/twilio/rest/preview/sync/service/document/document_permission.py +++ /dev/null @@ -1,443 +0,0 @@ -# coding=utf-8 -r""" -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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the DocumentPermissionInstance - - :returns: The fetched DocumentPermissionInstance - :rtype: twilio.rest.preview.sync.service.document.document_permission.DocumentPermissionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'document_sid': payload.get('document_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('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 the DocumentPermissionInstance - - :returns: The 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: The 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 05e2b02c8d..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,475 +0,0 @@ -# coding=utf-8 -r""" -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 the SyncListInstance - - :param unicode unique_name: The unique_name - - :returns: The created SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncListInstance - - :returns: The fetched SyncListInstance - :rtype: twilio.rest.preview.sync.service.sync_list.SyncListInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 the SyncListInstance - - :returns: The 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 2b427e6a28..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py +++ /dev/null @@ -1,515 +0,0 @@ -# coding=utf-8 -r""" -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 the SyncListItemInstance - - :param dict data: The data - - :returns: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncListItemInstance - - :returns: The fetched SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=self._solution['index'], - ) - - def delete(self, if_match=values.unset): - """ - Deletes the SyncListItemInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'If-Match': if_match, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def update(self, data, if_match=values.unset): - """ - Update the SyncListItemInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - data = values.of({'Data': serialize.object(data), }) - headers = values.of({'If-Match': if_match, }) - - 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'], - ) - - 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.get('index')), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'list_sid': payload.get('list_sid'), - 'url': payload.get('url'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 the SyncListItemInstance - - :returns: The fetched SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - return self._proxy.fetch() - - def delete(self, if_match=values.unset): - """ - Deletes the SyncListItemInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(if_match=if_match, ) - - def update(self, data, if_match=values.unset): - """ - Update the SyncListItemInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance - """ - return self._proxy.update(data, if_match=if_match, ) - - 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 3a0bb2afb7..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py +++ /dev/null @@ -1,443 +0,0 @@ -# coding=utf-8 -r""" -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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncListPermissionInstance - - :returns: The fetched SyncListPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'list_sid': payload.get('list_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('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 the SyncListPermissionInstance - - :returns: The 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: The 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 9d6d4e6ca7..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,475 +0,0 @@ -# coding=utf-8 -r""" -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 the SyncMapInstance - - :param unicode unique_name: The unique_name - - :returns: The created SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncMapInstance - - :returns: The fetched SyncMapInstance - :rtype: twilio.rest.preview.sync.service.sync_map.SyncMapInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 the SyncMapInstance - - :returns: The 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 81d3aa01cc..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py +++ /dev/null @@ -1,516 +0,0 @@ -# coding=utf-8 -r""" -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 the SyncMapItemInstance - - :param unicode key: The key - :param dict data: The data - - :returns: The 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(method='POST', uri=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']) - - 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 - """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncMapItemInstance - - :returns: The fetched SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=self._solution['key'], - ) - - def delete(self, if_match=values.unset): - """ - Deletes the SyncMapItemInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'If-Match': if_match, }) - - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) - - def update(self, data, if_match=values.unset): - """ - Update the SyncMapItemInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - data = values.of({'Data': serialize.object(data), }) - headers = values.of({'If-Match': if_match, }) - - 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'], - ) - - 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.get('key'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'map_sid': payload.get('map_sid'), - 'url': payload.get('url'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 the SyncMapItemInstance - - :returns: The fetched SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - return self._proxy.fetch() - - def delete(self, if_match=values.unset): - """ - Deletes the SyncMapItemInstance - - :param unicode if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._proxy.delete(if_match=if_match, ) - - def update(self, data, if_match=values.unset): - """ - Update the SyncMapItemInstance - - :param dict data: The data - :param unicode if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemInstance - """ - return self._proxy.update(data, if_match=if_match, ) - - 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 765ca6ee07..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py +++ /dev/null @@ -1,443 +0,0 @@ -# coding=utf-8 -r""" -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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the SyncMapPermissionInstance - - :returns: The fetched SyncMapPermissionInstance - :rtype: twilio.rest.preview.sync.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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: The 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(method='POST', uri=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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'map_sid': payload.get('map_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('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 the SyncMapPermissionInstance - - :returns: The 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: The 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/trusted_comms/__init__.py b/twilio/rest/preview/trusted_comms/__init__.py deleted file mode 100644 index fc352960d9..0000000000 --- a/twilio/rest/preview/trusted_comms/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.version import Version -from twilio.rest.preview.trusted_comms.branded_call import BrandedCallList -from twilio.rest.preview.trusted_comms.brands_information import BrandsInformationList -from twilio.rest.preview.trusted_comms.business import BusinessList -from twilio.rest.preview.trusted_comms.cps import CpsList -from twilio.rest.preview.trusted_comms.current_call import CurrentCallList -from twilio.rest.preview.trusted_comms.phone_call import PhoneCallList - - -class TrustedComms(Version): - - def __init__(self, domain): - """ - Initialize the TrustedComms version of Preview - - :returns: TrustedComms version of Preview - :rtype: twilio.rest.preview.trusted_comms.TrustedComms.TrustedComms - """ - super(TrustedComms, self).__init__(domain) - self.version = 'TrustedComms' - self._branded_calls = None - self._brands_information = None - self._businesses = None - self._cps = None - self._current_calls = None - self._phone_calls = None - - @property - def branded_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallList - """ - if self._branded_calls is None: - self._branded_calls = BrandedCallList(self) - return self._branded_calls - - @property - def brands_information(self): - """ - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationList - """ - if self._brands_information is None: - self._brands_information = BrandsInformationList(self) - return self._brands_information - - @property - def businesses(self): - """ - :rtype: twilio.rest.preview.trusted_comms.business.BusinessList - """ - if self._businesses is None: - self._businesses = BusinessList(self) - return self._businesses - - @property - def cps(self): - """ - :rtype: twilio.rest.preview.trusted_comms.cps.CpsList - """ - if self._cps is None: - self._cps = CpsList(self) - return self._cps - - @property - def current_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallList - """ - if self._current_calls is None: - self._current_calls = CurrentCallList(self) - return self._current_calls - - @property - def phone_calls(self): - """ - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallList - """ - if self._phone_calls is None: - self._phone_calls = PhoneCallList(self) - return self._phone_calls - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/trusted_comms/branded_call.py b/twilio/rest/preview/trusted_comms/branded_call.py deleted file mode 100644 index ba1461c081..0000000000 --- a/twilio/rest/preview/trusted_comms/branded_call.py +++ /dev/null @@ -1,296 +0,0 @@ -# coding=utf-8 -r""" -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 BrandedCallList(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 BrandedCallList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallList - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallList - """ - super(BrandedCallList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Business/BrandedCalls'.format(**self._solution) - - def create(self, from_, to, reason, call_sid=values.unset): - """ - Create the BrandedCallInstance - - :param unicode from_: Twilio number from which to brand the call - :param unicode to: The terminating Phone Number - :param unicode reason: The business reason for this phone call - :param unicode call_sid: The Call sid this Branded Call should link to - - :returns: The created BrandedCallInstance - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallInstance - """ - data = values.of({'From': from_, 'To': to, 'Reason': reason, 'CallSid': call_sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return BrandedCallInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandedCallPage(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 BrandedCallPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage - """ - super(BrandedCallPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BrandedCallInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallInstance - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallInstance - """ - return BrandedCallInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandedCallInstance(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): - """ - Initialize the BrandedCallInstance - - :returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallInstance - :rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallInstance - """ - super(BrandedCallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'bg_color': payload.get('bg_color'), - 'brand_sid': payload.get('brand_sid'), - 'branded_channel_sid': payload.get('branded_channel_sid'), - 'business_sid': payload.get('business_sid'), - 'call_sid': payload.get('call_sid'), - 'caller': payload.get('caller'), - 'created_at': deserialize.iso8601_datetime(payload.get('created_at')), - 'font_color': payload.get('font_color'), - 'from_': payload.get('from'), - 'logo': payload.get('logo'), - 'phone_number_sid': payload.get('phone_number_sid'), - 'reason': payload.get('reason'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'to': payload.get('to'), - 'url': payload.get('url'), - 'use_case': payload.get('use_case'), - } - - # Context - self._context = None - self._solution = {} - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def bg_color(self): - """ - :returns: Background color of the current phone call - :rtype: unicode - """ - return self._properties['bg_color'] - - @property - def brand_sid(self): - """ - :returns: Brand Sid. - :rtype: unicode - """ - return self._properties['brand_sid'] - - @property - def branded_channel_sid(self): - """ - :returns: Branded Channel Sid. - :rtype: unicode - """ - return self._properties['branded_channel_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def call_sid(self): - """ - :returns: A string that uniquely identifies this phone call. - :rtype: unicode - """ - return self._properties['call_sid'] - - @property - def caller(self): - """ - :returns: Caller name of the current phone call - :rtype: unicode - """ - return self._properties['caller'] - - @property - def created_at(self): - """ - :returns: The date this current phone call was created - :rtype: datetime - """ - return self._properties['created_at'] - - @property - def font_color(self): - """ - :returns: Font color of the current phone call - :rtype: unicode - """ - return self._properties['font_color'] - - @property - def from_(self): - """ - :returns: The originating phone number - :rtype: unicode - """ - return self._properties['from_'] - - @property - def logo(self): - """ - :returns: Logo URL of the caller - :rtype: unicode - """ - return self._properties['logo'] - - @property - def phone_number_sid(self): - """ - :returns: Phone Number Sid. - :rtype: unicode - """ - return self._properties['phone_number_sid'] - - @property - def reason(self): - """ - :returns: The business reason for this current phone call - :rtype: unicode - """ - return self._properties['reason'] - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this current branded phone call. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status of the current phone call - :rtype: unicode - """ - return self._properties['status'] - - @property - def to(self): - """ - :returns: The terminating phone number - :rtype: unicode - """ - return self._properties['to'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def use_case(self): - """ - :returns: The use case for the current phone call - :rtype: unicode - """ - return self._properties['use_case'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/trusted_comms/brands_information.py b/twilio/rest/preview/trusted_comms/brands_information.py deleted file mode 100644 index 7a6651f107..0000000000 --- a/twilio/rest/preview/trusted_comms/brands_information.py +++ /dev/null @@ -1,241 +0,0 @@ -# coding=utf-8 -r""" -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 BrandsInformationList(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 BrandsInformationList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationList - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationList - """ - super(BrandsInformationList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self): - """ - Constructs a BrandsInformationContext - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - """ - return BrandsInformationContext(self._version, ) - - def __call__(self): - """ - Constructs a BrandsInformationContext - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - """ - return BrandsInformationContext(self._version, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandsInformationPage(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 BrandsInformationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationPage - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationPage - """ - super(BrandsInformationPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BrandsInformationInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - """ - return BrandsInformationInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandsInformationContext(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): - """ - Initialize the BrandsInformationContext - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - """ - super(BrandsInformationContext, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/BrandsInformation'.format(**self._solution) - - def fetch(self, if_none_match=values.unset): - """ - Fetch the BrandsInformationInstance - - :param unicode if_none_match: Standard `If-None-Match` HTTP header - - :returns: The fetched BrandsInformationInstance - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - """ - headers = values.of({'If-None-Match': if_none_match, }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return BrandsInformationInstance(self._version, payload, ) - - 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 BrandsInformationInstance(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): - """ - Initialize the BrandsInformationInstance - - :returns: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - """ - super(BrandsInformationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'update_time': deserialize.iso8601_datetime(payload.get('update_time')), - 'file_link': payload.get('file_link'), - 'file_link_ttl_in_seconds': payload.get('file_link_ttl_in_seconds'), - 'url': payload.get('url'), - } - - # Context - self._context = None - 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 - - :returns: BrandsInformationContext for this BrandsInformationInstance - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationContext - """ - if self._context is None: - self._context = BrandsInformationContext(self._version, ) - return self._context - - @property - def update_time(self): - """ - :returns: Creation time of the information retrieved - :rtype: datetime - """ - return self._properties['update_time'] - - @property - def file_link(self): - """ - :returns: The URL to the brands information - :rtype: unicode - """ - return self._properties['file_link'] - - @property - def file_link_ttl_in_seconds(self): - """ - :returns: How long will be the `file_link` valid - :rtype: unicode - """ - return self._properties['file_link_ttl_in_seconds'] - - @property - def url(self): - """ - :returns: The URL of this resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self, if_none_match=values.unset): - """ - Fetch the BrandsInformationInstance - - :param unicode if_none_match: Standard `If-None-Match` HTTP header - - :returns: The fetched BrandsInformationInstance - :rtype: twilio.rest.preview.trusted_comms.brands_information.BrandsInformationInstance - """ - return self._proxy.fetch(if_none_match=if_none_match, ) - - 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/trusted_comms/business/__init__.py b/twilio/rest/preview/trusted_comms/business/__init__.py deleted file mode 100644 index 81d259ea92..0000000000 --- a/twilio/rest/preview/trusted_comms/business/__init__.py +++ /dev/null @@ -1,289 +0,0 @@ -# coding=utf-8 -r""" -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.trusted_comms.business.brand import BrandList -from twilio.rest.preview.trusted_comms.business.insights import InsightsList - - -class BusinessList(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 BusinessList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.business.BusinessList - :rtype: twilio.rest.preview.trusted_comms.business.BusinessList - """ - super(BusinessList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self, sid): - """ - Constructs a BusinessContext - - :param sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.BusinessContext - :rtype: twilio.rest.preview.trusted_comms.business.BusinessContext - """ - return BusinessContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a BusinessContext - - :param sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.BusinessContext - :rtype: twilio.rest.preview.trusted_comms.business.BusinessContext - """ - return BusinessContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BusinessPage(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 BusinessPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.business.BusinessPage - :rtype: twilio.rest.preview.trusted_comms.business.BusinessPage - """ - super(BusinessPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BusinessInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.BusinessInstance - :rtype: twilio.rest.preview.trusted_comms.business.BusinessInstance - """ - return BusinessInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BusinessContext(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 BusinessContext - - :param Version version: Version that contains the resource - :param sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.BusinessContext - :rtype: twilio.rest.preview.trusted_comms.business.BusinessContext - """ - super(BusinessContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Businesses/{sid}'.format(**self._solution) - - # Dependents - self._brands = None - self._insights = None - - def fetch(self): - """ - Fetch the BusinessInstance - - :returns: The fetched BusinessInstance - :rtype: twilio.rest.preview.trusted_comms.business.BusinessInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return BusinessInstance(self._version, payload, sid=self._solution['sid'], ) - - @property - def brands(self): - """ - Access the brands - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandList - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandList - """ - if self._brands is None: - self._brands = BrandList(self._version, business_sid=self._solution['sid'], ) - return self._brands - - @property - def insights(self): - """ - Access the insights - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsList - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsList - """ - if self._insights is None: - self._insights = InsightsList(self._version, business_sid=self._solution['sid'], ) - return self._insights - - 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 BusinessInstance(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 BusinessInstance - - :returns: twilio.rest.preview.trusted_comms.business.BusinessInstance - :rtype: twilio.rest.preview.trusted_comms.business.BusinessInstance - """ - super(BusinessInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'links': payload.get('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: BusinessContext for this BusinessInstance - :rtype: twilio.rest.preview.trusted_comms.business.BusinessContext - """ - if self._context is None: - self._context = BusinessContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Business. - :rtype: unicode - """ - return self._properties['sid'] - - @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 the BusinessInstance - - :returns: The fetched BusinessInstance - :rtype: twilio.rest.preview.trusted_comms.business.BusinessInstance - """ - return self._proxy.fetch() - - @property - def brands(self): - """ - Access the brands - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandList - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandList - """ - return self._proxy.brands - - @property - def insights(self): - """ - Access the insights - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsList - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsList - """ - return self._proxy.insights - - 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/trusted_comms/business/brand/__init__.py b/twilio/rest/preview/trusted_comms/business/brand/__init__.py deleted file mode 100644 index 284de18b89..0000000000 --- a/twilio/rest/preview/trusted_comms/business/brand/__init__.py +++ /dev/null @@ -1,290 +0,0 @@ -# coding=utf-8 -r""" -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.trusted_comms.business.brand.branded_channel import BrandedChannelList - - -class BrandList(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, business_sid): - """ - Initialize the BrandList - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandList - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandList - """ - super(BrandList, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, } - - def get(self, sid): - """ - Constructs a BrandContext - - :param sid: Brand Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandContext - """ - return BrandContext(self._version, business_sid=self._solution['business_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a BrandContext - - :param sid: Brand Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandContext - """ - return BrandContext(self._version, business_sid=self._solution['business_sid'], sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandPage(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 BrandPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param business_sid: Business Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandPage - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandPage - """ - super(BrandPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BrandInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - """ - return BrandInstance(self._version, payload, business_sid=self._solution['business_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandContext(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, business_sid, sid): - """ - Initialize the BrandContext - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - :param sid: Brand Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandContext - """ - super(BrandContext, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, 'sid': sid, } - self._uri = '/Businesses/{business_sid}/Brands/{sid}'.format(**self._solution) - - # Dependents - self._branded_channels = None - - def fetch(self): - """ - Fetch the BrandInstance - - :returns: The fetched BrandInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return BrandInstance( - self._version, - payload, - business_sid=self._solution['business_sid'], - sid=self._solution['sid'], - ) - - @property - def branded_channels(self): - """ - Access the branded_channels - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - """ - if self._branded_channels is None: - self._branded_channels = BrandedChannelList( - self._version, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['sid'], - ) - return self._branded_channels - - 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 BrandInstance(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, business_sid, sid=None): - """ - Initialize the BrandInstance - - :returns: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - """ - super(BrandInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'business_sid': payload.get('business_sid'), - 'sid': payload.get('sid'), - 'links': payload.get('links'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'business_sid': business_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: BrandContext for this BrandInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandContext - """ - if self._context is None: - self._context = BrandContext( - self._version, - business_sid=self._solution['business_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def sid(self): - """ - :returns: Brand Sid. - :rtype: unicode - """ - return self._properties['sid'] - - @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 the BrandInstance - - :returns: The fetched BrandInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.BrandInstance - """ - return self._proxy.fetch() - - @property - def branded_channels(self): - """ - Access the branded_channels - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - """ - return self._proxy.branded_channels - - 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/trusted_comms/business/brand/branded_channel/__init__.py b/twilio/rest/preview/trusted_comms/business/brand/branded_channel/__init__.py deleted file mode 100644 index cc5357b034..0000000000 --- a/twilio/rest/preview/trusted_comms/business/brand/branded_channel/__init__.py +++ /dev/null @@ -1,324 +0,0 @@ -# coding=utf-8 -r""" -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.trusted_comms.business.brand.branded_channel.channel import ChannelList - - -class BrandedChannelList(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, business_sid, brand_sid): - """ - Initialize the BrandedChannelList - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - :param brand_sid: Brand Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelList - """ - super(BrandedChannelList, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, 'brand_sid': brand_sid, } - - def get(self, sid): - """ - Constructs a BrandedChannelContext - - :param sid: Branded Channel Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - """ - return BrandedChannelContext( - self._version, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a BrandedChannelContext - - :param sid: Branded Channel Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - """ - return BrandedChannelContext( - self._version, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - sid=sid, - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandedChannelPage(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 BrandedChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param business_sid: Business Sid. - :param brand_sid: Brand Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelPage - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelPage - """ - super(BrandedChannelPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BrandedChannelInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - """ - return BrandedChannelInstance( - self._version, - payload, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BrandedChannelContext(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, business_sid, brand_sid, sid): - """ - Initialize the BrandedChannelContext - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - :param brand_sid: Brand Sid. - :param sid: Branded Channel Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - """ - super(BrandedChannelContext, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, 'brand_sid': brand_sid, 'sid': sid, } - self._uri = '/Businesses/{business_sid}/Brands/{brand_sid}/BrandedChannels/{sid}'.format(**self._solution) - - # Dependents - self._channels = None - - def fetch(self): - """ - Fetch the BrandedChannelInstance - - :returns: The fetched BrandedChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return BrandedChannelInstance( - self._version, - payload, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - sid=self._solution['sid'], - ) - - @property - def channels(self): - """ - Access the channels - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - """ - if self._channels is None: - self._channels = ChannelList( - self._version, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - branded_channel_sid=self._solution['sid'], - ) - return self._channels - - 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 BrandedChannelInstance(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, business_sid, brand_sid, sid=None): - """ - Initialize the BrandedChannelInstance - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - """ - super(BrandedChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'business_sid': payload.get('business_sid'), - 'brand_sid': payload.get('brand_sid'), - 'sid': payload.get('sid'), - 'links': payload.get('links'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'business_sid': business_sid, - 'brand_sid': brand_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: BrandedChannelContext for this BrandedChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelContext - """ - if self._context is None: - self._context = BrandedChannelContext( - self._version, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def brand_sid(self): - """ - :returns: Brand Sid. - :rtype: unicode - """ - return self._properties['brand_sid'] - - @property - def sid(self): - """ - :returns: Branded Channel Sid. - :rtype: unicode - """ - return self._properties['sid'] - - @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 the BrandedChannelInstance - - :returns: The fetched BrandedChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.BrandedChannelInstance - """ - return self._proxy.fetch() - - @property - def channels(self): - """ - Access the channels - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - """ - return self._proxy.channels - - 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/trusted_comms/business/brand/branded_channel/channel.py b/twilio/rest/preview/trusted_comms/business/brand/branded_channel/channel.py deleted file mode 100644 index 10b5060273..0000000000 --- a/twilio/rest/preview/trusted_comms/business/brand/branded_channel/channel.py +++ /dev/null @@ -1,220 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 ChannelList(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, business_sid, brand_sid, branded_channel_sid): - """ - Initialize the ChannelList - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - :param brand_sid: Brand Sid. - :param branded_channel_sid: Branded Channel Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelList - """ - super(ChannelList, self).__init__(version) - - # Path Solution - self._solution = { - 'business_sid': business_sid, - 'brand_sid': brand_sid, - 'branded_channel_sid': branded_channel_sid, - } - self._uri = '/Businesses/{business_sid}/Brands/{brand_sid}/BrandedChannels/{branded_channel_sid}/Channels'.format(**self._solution) - - def create(self, phone_number_sid): - """ - Create the ChannelInstance - - :param unicode phone_number_sid: Phone Number Sid to be branded. - - :returns: The created ChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelInstance - """ - data = values.of({'PhoneNumberSid': phone_number_sid, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ChannelInstance( - self._version, - payload, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - branded_channel_sid=self._solution['branded_channel_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ChannelPage(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 ChannelPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param business_sid: Business Sid. - :param brand_sid: Brand Sid. - :param branded_channel_sid: Branded Channel Sid. - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelPage - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelPage - """ - super(ChannelPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ChannelInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelInstance - """ - return ChannelInstance( - self._version, - payload, - business_sid=self._solution['business_sid'], - brand_sid=self._solution['brand_sid'], - branded_channel_sid=self._solution['branded_channel_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ChannelInstance(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, business_sid, brand_sid, - branded_channel_sid): - """ - Initialize the ChannelInstance - - :returns: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelInstance - :rtype: twilio.rest.preview.trusted_comms.business.brand.branded_channel.channel.ChannelInstance - """ - super(ChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'business_sid': payload.get('business_sid'), - 'brand_sid': payload.get('brand_sid'), - 'branded_channel_sid': payload.get('branded_channel_sid'), - 'phone_number_sid': payload.get('phone_number_sid'), - 'phone_number': payload.get('phone_number'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'business_sid': business_sid, - 'brand_sid': brand_sid, - 'branded_channel_sid': branded_channel_sid, - } - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def brand_sid(self): - """ - :returns: Brand Sid. - :rtype: unicode - """ - return self._properties['brand_sid'] - - @property - def branded_channel_sid(self): - """ - :returns: Branded Channel Sid. - :rtype: unicode - """ - return self._properties['branded_channel_sid'] - - @property - def phone_number_sid(self): - """ - :returns: Phone Number Sid to be branded. - :rtype: unicode - """ - return self._properties['phone_number_sid'] - - @property - def phone_number(self): - """ - :returns: Twilio number to assign to the Branded Channel - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/trusted_comms/business/insights/__init__.py b/twilio/rest/preview/trusted_comms/business/insights/__init__.py deleted file mode 100644 index 65d4712970..0000000000 --- a/twilio/rest/preview/trusted_comms/business/insights/__init__.py +++ /dev/null @@ -1,130 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.page import Page -from twilio.rest.preview.trusted_comms.business.insights.impressions_rate import ImpressionsRateList - - -class InsightsList(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, business_sid): - """ - Initialize the InsightsList - - :param Version version: Version that contains the resource - :param business_sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsList - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsList - """ - super(InsightsList, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, } - - # Components - self._impressions_rate = None - - @property - def impressions_rate(self): - """ - Access the impressions_rate - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateList - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateList - """ - if self._impressions_rate is None: - self._impressions_rate = ImpressionsRateList( - self._version, - business_sid=self._solution['business_sid'], - ) - return self._impressions_rate - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class InsightsPage(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 InsightsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param business_sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsPage - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsPage - """ - super(InsightsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of InsightsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsInstance - """ - return InsightsInstance(self._version, payload, business_sid=self._solution['business_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class InsightsInstance(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, business_sid): - """ - Initialize the InsightsInstance - - :returns: twilio.rest.preview.trusted_comms.business.insights.InsightsInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.InsightsInstance - """ - super(InsightsInstance, self).__init__(version) - - # Context - self._context = None - self._solution = {'business_sid': business_sid, } - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/trusted_comms/business/insights/impressions_rate.py b/twilio/rest/preview/trusted_comms/business/insights/impressions_rate.py deleted file mode 100644 index b6b80ed06c..0000000000 --- a/twilio/rest/preview/trusted_comms/business/insights/impressions_rate.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding=utf-8 -r""" -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 ImpressionsRateList(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, business_sid): - """ - Initialize the ImpressionsRateList - - :param Version version: Version that contains the resource - :param business_sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateList - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateList - """ - super(ImpressionsRateList, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, } - - def get(self): - """ - Constructs a ImpressionsRateContext - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - """ - return ImpressionsRateContext(self._version, business_sid=self._solution['business_sid'], ) - - def __call__(self): - """ - Constructs a ImpressionsRateContext - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - """ - return ImpressionsRateContext(self._version, business_sid=self._solution['business_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ImpressionsRatePage(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 ImpressionsRatePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param business_sid: A string that uniquely identifies this Business. - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRatePage - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRatePage - """ - super(ImpressionsRatePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ImpressionsRateInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - """ - return ImpressionsRateInstance(self._version, payload, business_sid=self._solution['business_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class ImpressionsRateContext(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, business_sid): - """ - Initialize the ImpressionsRateContext - - :param Version version: Version that contains the resource - :param business_sid: Business Sid. - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - """ - super(ImpressionsRateContext, self).__init__(version) - - # Path Solution - self._solution = {'business_sid': business_sid, } - self._uri = '/Businesses/{business_sid}/Insights/ImpressionsRate'.format(**self._solution) - - def fetch(self, brand_sid=values.unset, branded_channel_sid=values.unset, - phone_number_sid=values.unset, country=values.unset, - start=values.unset, end=values.unset, interval=values.unset): - """ - Fetch the ImpressionsRateInstance - - :param unicode brand_sid: Brand Sid. - :param unicode branded_channel_sid: Branded Channel Sid. - :param unicode phone_number_sid: Phone Number Sid. - :param unicode country: Country 2-letter ISO 3166 code. - :param datetime start: The start date that for this Impressions Rate. - :param datetime end: The end date that for this Impressions Rate. - :param ImpressionsRateInstance.Intervals interval: The Interval of this Impressions Rate. - - :returns: The fetched ImpressionsRateInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - """ - data = values.of({ - 'BrandSid': brand_sid, - 'BrandedChannelSid': branded_channel_sid, - 'PhoneNumberSid': phone_number_sid, - 'Country': country, - 'Start': serialize.iso8601_datetime(start), - 'End': serialize.iso8601_datetime(end), - 'Interval': interval, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - - return ImpressionsRateInstance(self._version, payload, business_sid=self._solution['business_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 ImpressionsRateInstance(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 Intervals(object): - MINUTE = "minute" - HOUR = "hour" - DAY = "day" - WEEK = "week" - MONTH = "month" - - def __init__(self, version, payload, business_sid): - """ - Initialize the ImpressionsRateInstance - - :returns: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - """ - super(ImpressionsRateInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'business_sid': payload.get('business_sid'), - 'end': deserialize.iso8601_datetime(payload.get('end')), - 'interval': payload.get('interval'), - 'reports': payload.get('reports'), - 'start': deserialize.iso8601_datetime(payload.get('start')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'business_sid': business_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: ImpressionsRateContext for this ImpressionsRateInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateContext - """ - if self._context is None: - self._context = ImpressionsRateContext(self._version, business_sid=self._solution['business_sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def end(self): - """ - :returns: The end date that for this Impressions Rate. - :rtype: datetime - """ - return self._properties['end'] - - @property - def interval(self): - """ - :returns: The Interval of this Impressions Rate. - :rtype: ImpressionsRateInstance.Intervals - """ - return self._properties['interval'] - - @property - def reports(self): - """ - :returns: Values of Impressions Rate per interval. - :rtype: dict - """ - return self._properties['reports'] - - @property - def start(self): - """ - :returns: The start date that for this Impressions Rate. - :rtype: datetime - """ - return self._properties['start'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self, brand_sid=values.unset, branded_channel_sid=values.unset, - phone_number_sid=values.unset, country=values.unset, - start=values.unset, end=values.unset, interval=values.unset): - """ - Fetch the ImpressionsRateInstance - - :param unicode brand_sid: Brand Sid. - :param unicode branded_channel_sid: Branded Channel Sid. - :param unicode phone_number_sid: Phone Number Sid. - :param unicode country: Country 2-letter ISO 3166 code. - :param datetime start: The start date that for this Impressions Rate. - :param datetime end: The end date that for this Impressions Rate. - :param ImpressionsRateInstance.Intervals interval: The Interval of this Impressions Rate. - - :returns: The fetched ImpressionsRateInstance - :rtype: twilio.rest.preview.trusted_comms.business.insights.impressions_rate.ImpressionsRateInstance - """ - return self._proxy.fetch( - brand_sid=brand_sid, - branded_channel_sid=branded_channel_sid, - phone_number_sid=phone_number_sid, - country=country, - start=start, - end=end, - interval=interval, - ) - - 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/trusted_comms/cps.py b/twilio/rest/preview/trusted_comms/cps.py deleted file mode 100644 index 2c1039e62c..0000000000 --- a/twilio/rest/preview/trusted_comms/cps.py +++ /dev/null @@ -1,231 +0,0 @@ -# coding=utf-8 -r""" -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 CpsList(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 CpsList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.cps.CpsList - :rtype: twilio.rest.preview.trusted_comms.cps.CpsList - """ - super(CpsList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self): - """ - Constructs a CpsContext - - :returns: twilio.rest.preview.trusted_comms.cps.CpsContext - :rtype: twilio.rest.preview.trusted_comms.cps.CpsContext - """ - return CpsContext(self._version, ) - - def __call__(self): - """ - Constructs a CpsContext - - :returns: twilio.rest.preview.trusted_comms.cps.CpsContext - :rtype: twilio.rest.preview.trusted_comms.cps.CpsContext - """ - return CpsContext(self._version, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CpsPage(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 CpsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.cps.CpsPage - :rtype: twilio.rest.preview.trusted_comms.cps.CpsPage - """ - super(CpsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CpsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.cps.CpsInstance - :rtype: twilio.rest.preview.trusted_comms.cps.CpsInstance - """ - return CpsInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CpsContext(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): - """ - Initialize the CpsContext - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.cps.CpsContext - :rtype: twilio.rest.preview.trusted_comms.cps.CpsContext - """ - super(CpsContext, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/CPS'.format(**self._solution) - - def fetch(self, x_xcnam_sensitive_phone_number=values.unset): - """ - Fetch the CpsInstance - - :param unicode x_xcnam_sensitive_phone_number: Phone number to retrieve CPS. - - :returns: The fetched CpsInstance - :rtype: twilio.rest.preview.trusted_comms.cps.CpsInstance - """ - headers = values.of({'X-Xcnam-Sensitive-Phone-Number': x_xcnam_sensitive_phone_number, }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return CpsInstance(self._version, payload, ) - - 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 CpsInstance(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): - """ - Initialize the CpsInstance - - :returns: twilio.rest.preview.trusted_comms.cps.CpsInstance - :rtype: twilio.rest.preview.trusted_comms.cps.CpsInstance - """ - super(CpsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'cps_url': payload.get('cps_url'), - 'phone_number': payload.get('phone_number'), - 'url': payload.get('url'), - } - - # Context - self._context = None - 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 - - :returns: CpsContext for this CpsInstance - :rtype: twilio.rest.preview.trusted_comms.cps.CpsContext - """ - if self._context is None: - self._context = CpsContext(self._version, ) - return self._context - - @property - def cps_url(self): - """ - :returns: CPS URL of the phone number. - :rtype: unicode - """ - return self._properties['cps_url'] - - @property - def phone_number(self): - """ - :returns: Phone number passed. - :rtype: unicode - """ - return self._properties['phone_number'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self, x_xcnam_sensitive_phone_number=values.unset): - """ - Fetch the CpsInstance - - :param unicode x_xcnam_sensitive_phone_number: Phone number to retrieve CPS. - - :returns: The fetched CpsInstance - :rtype: twilio.rest.preview.trusted_comms.cps.CpsInstance - """ - return self._proxy.fetch(x_xcnam_sensitive_phone_number=x_xcnam_sensitive_phone_number, ) - - 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/trusted_comms/current_call.py b/twilio/rest/preview/trusted_comms/current_call.py deleted file mode 100644 index 436cc83666..0000000000 --- a/twilio/rest/preview/trusted_comms/current_call.py +++ /dev/null @@ -1,341 +0,0 @@ -# coding=utf-8 -r""" -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 CurrentCallList(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 CurrentCallList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallList - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallList - """ - super(CurrentCallList, self).__init__(version) - - # Path Solution - self._solution = {} - - def get(self): - """ - Constructs a CurrentCallContext - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - """ - return CurrentCallContext(self._version, ) - - def __call__(self): - """ - Constructs a CurrentCallContext - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - """ - return CurrentCallContext(self._version, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CurrentCallPage(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 CurrentCallPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallPage - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallPage - """ - super(CurrentCallPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CurrentCallInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - """ - return CurrentCallInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class CurrentCallContext(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): - """ - Initialize the CurrentCallContext - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - """ - super(CurrentCallContext, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/CurrentCall'.format(**self._solution) - - def fetch(self, x_xcnam_sensitive_phone_number_from=values.unset, - x_xcnam_sensitive_phone_number_to=values.unset): - """ - Fetch the CurrentCallInstance - - :param unicode x_xcnam_sensitive_phone_number_from: The originating Phone Number - :param unicode x_xcnam_sensitive_phone_number_to: The terminating Phone Number - - :returns: The fetched CurrentCallInstance - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - """ - headers = values.of({ - 'X-Xcnam-Sensitive-Phone-Number-From': x_xcnam_sensitive_phone_number_from, - 'X-Xcnam-Sensitive-Phone-Number-To': x_xcnam_sensitive_phone_number_to, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) - - return CurrentCallInstance(self._version, payload, ) - - 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 CurrentCallInstance(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): - """ - Initialize the CurrentCallInstance - - :returns: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - """ - super(CurrentCallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'bg_color': payload.get('bg_color'), - 'caller': payload.get('caller'), - 'created_at': deserialize.iso8601_datetime(payload.get('created_at')), - 'font_color': payload.get('font_color'), - 'from_': payload.get('from'), - 'logo': payload.get('logo'), - 'manager': payload.get('manager'), - 'reason': payload.get('reason'), - 'shield_img': payload.get('shield_img'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'to': payload.get('to'), - 'url': payload.get('url'), - 'use_case': payload.get('use_case'), - } - - # Context - self._context = None - 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 - - :returns: CurrentCallContext for this CurrentCallInstance - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallContext - """ - if self._context is None: - self._context = CurrentCallContext(self._version, ) - return self._context - - @property - def bg_color(self): - """ - :returns: Background color of the current phone call - :rtype: unicode - """ - return self._properties['bg_color'] - - @property - def caller(self): - """ - :returns: Caller name of the current phone call - :rtype: unicode - """ - return self._properties['caller'] - - @property - def created_at(self): - """ - :returns: The date this current phone call was created - :rtype: datetime - """ - return self._properties['created_at'] - - @property - def font_color(self): - """ - :returns: Font color of the current phone call - :rtype: unicode - """ - return self._properties['font_color'] - - @property - def from_(self): - """ - :returns: The originating phone number - :rtype: unicode - """ - return self._properties['from_'] - - @property - def logo(self): - """ - :returns: Logo URL of the caller - :rtype: unicode - """ - return self._properties['logo'] - - @property - def manager(self): - """ - :returns: The name of the CPS organization - :rtype: unicode - """ - return self._properties['manager'] - - @property - def reason(self): - """ - :returns: The business reason for this current phone call - :rtype: unicode - """ - return self._properties['reason'] - - @property - def shield_img(self): - """ - :returns: Shield image URL that serves as authenticity proof of the current phone call - :rtype: unicode - """ - return self._properties['shield_img'] - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this current branded phone call. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status of the current phone call - :rtype: unicode - """ - return self._properties['status'] - - @property - def to(self): - """ - :returns: The terminating phone number - :rtype: unicode - """ - return self._properties['to'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def use_case(self): - """ - :returns: The use case for the current phone call - :rtype: unicode - """ - return self._properties['use_case'] - - def fetch(self, x_xcnam_sensitive_phone_number_from=values.unset, - x_xcnam_sensitive_phone_number_to=values.unset): - """ - Fetch the CurrentCallInstance - - :param unicode x_xcnam_sensitive_phone_number_from: The originating Phone Number - :param unicode x_xcnam_sensitive_phone_number_to: The terminating Phone Number - - :returns: The fetched CurrentCallInstance - :rtype: twilio.rest.preview.trusted_comms.current_call.CurrentCallInstance - """ - return self._proxy.fetch( - x_xcnam_sensitive_phone_number_from=x_xcnam_sensitive_phone_number_from, - x_xcnam_sensitive_phone_number_to=x_xcnam_sensitive_phone_number_to, - ) - - 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/trusted_comms/phone_call.py b/twilio/rest/preview/trusted_comms/phone_call.py deleted file mode 100644 index ec4057eb56..0000000000 --- a/twilio/rest/preview/trusted_comms/phone_call.py +++ /dev/null @@ -1,363 +0,0 @@ -# coding=utf-8 -r""" -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 PhoneCallList(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 PhoneCallList - - :param Version version: Version that contains the resource - - :returns: twilio.rest.preview.trusted_comms.phone_call.PhoneCallList - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallList - """ - super(PhoneCallList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Business/PhoneCalls'.format(**self._solution) - - def create(self, from_, to, reason=values.unset, application_sid=values.unset, - caller_id=values.unset, fallback_method=values.unset, - fallback_url=values.unset, machine_detection=values.unset, - machine_detection_silence_timeout=values.unset, - machine_detection_speech_end_threshold=values.unset, - machine_detection_speech_threshold=values.unset, - machine_detection_timeout=values.unset, method=values.unset, - record=values.unset, recording_channels=values.unset, - recording_status_callback=values.unset, - recording_status_callback_event=values.unset, - recording_status_callback_method=values.unset, - send_digits=values.unset, sip_auth_password=values.unset, - sip_auth_username=values.unset, status_callback=values.unset, - status_callback_event=values.unset, - status_callback_method=values.unset, timeout=values.unset, - trim=values.unset, url=values.unset): - """ - Create the PhoneCallInstance - - :param unicode from_: Twilio number from which to originate the call - :param unicode to: The terminating Phone Number - :param unicode reason: The business reason for this phone call - :param unicode application_sid: Refers to the Voice API Initiate Call parameter - :param unicode caller_id: Refers to the Voice API Initiate Call parameter - :param unicode fallback_method: Refers to the Voice API Initiate Call parameter - :param unicode fallback_url: Refers to the Voice API Initiate Call parameter - :param unicode machine_detection: Refers to the Voice API Initiate Call parameter - :param unicode machine_detection_silence_timeout: Refers to the Voice API Initiate Call parameter - :param unicode machine_detection_speech_end_threshold: Refers to the Voice API Initiate Call parameter - :param unicode machine_detection_speech_threshold: Refers to the Voice API Initiate Call parameter - :param unicode machine_detection_timeout: Refers to the Voice API Initiate Call parameter - :param unicode method: Refers to the Voice API Initiate Call parameter - :param bool record: Refers to the Voice API Initiate Call parameter - :param unicode recording_channels: Refers to the Voice API Initiate Call parameter - :param unicode recording_status_callback: Refers to the Voice API Initiate Call parameter - :param unicode recording_status_callback_event: Refers to the Voice API Initiate Call parameter - :param unicode recording_status_callback_method: Refers to the Voice API Initiate Call parameter - :param unicode send_digits: Refers to the Voice API Initiate Call parameter - :param unicode sip_auth_password: Refers to the Voice API Initiate Call parameter - :param unicode sip_auth_username: Refers to the Voice API Initiate Call parameter - :param unicode status_callback: Refers to the Voice API Initiate Call parameter - :param unicode status_callback_event: Refers to the Voice API Initiate Call parameter - :param unicode status_callback_method: Refers to the Voice API Initiate Call parameter - :param unicode timeout: Refers to the Voice API Initiate Call parameter - :param unicode trim: Refers to the Voice API Initiate Call parameter - :param unicode url: Refers to the Voice API Initiate Call parameter - - :returns: The created PhoneCallInstance - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallInstance - """ - data = values.of({ - 'From': from_, - 'To': to, - 'Reason': reason, - 'ApplicationSid': application_sid, - 'CallerId': caller_id, - 'FallbackMethod': fallback_method, - 'FallbackUrl': fallback_url, - 'MachineDetection': machine_detection, - 'MachineDetectionSilenceTimeout': machine_detection_silence_timeout, - 'MachineDetectionSpeechEndThreshold': machine_detection_speech_end_threshold, - 'MachineDetectionSpeechThreshold': machine_detection_speech_threshold, - 'MachineDetectionTimeout': machine_detection_timeout, - 'Method': method, - 'Record': record, - 'RecordingChannels': recording_channels, - 'RecordingStatusCallback': recording_status_callback, - 'RecordingStatusCallbackEvent': serialize.map(recording_status_callback_event, lambda e: e), - 'RecordingStatusCallbackMethod': recording_status_callback_method, - 'SendDigits': send_digits, - 'SipAuthPassword': sip_auth_password, - 'SipAuthUsername': sip_auth_username, - 'StatusCallback': status_callback, - 'StatusCallbackEvent': serialize.map(status_callback_event, lambda e: e), - 'StatusCallbackMethod': status_callback_method, - 'Timeout': timeout, - 'Trim': trim, - 'Url': url, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return PhoneCallInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneCallPage(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 PhoneCallPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.preview.trusted_comms.phone_call.PhoneCallPage - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallPage - """ - super(PhoneCallPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of PhoneCallInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.trusted_comms.phone_call.PhoneCallInstance - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallInstance - """ - return PhoneCallInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class PhoneCallInstance(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): - """ - Initialize the PhoneCallInstance - - :returns: twilio.rest.preview.trusted_comms.phone_call.PhoneCallInstance - :rtype: twilio.rest.preview.trusted_comms.phone_call.PhoneCallInstance - """ - super(PhoneCallInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'bg_color': payload.get('bg_color'), - 'brand_sid': payload.get('brand_sid'), - 'branded_channel_sid': payload.get('branded_channel_sid'), - 'business_sid': payload.get('business_sid'), - 'call_sid': payload.get('call_sid'), - 'caller': payload.get('caller'), - 'created_at': deserialize.iso8601_datetime(payload.get('created_at')), - 'font_color': payload.get('font_color'), - 'from_': payload.get('from'), - 'logo': payload.get('logo'), - 'phone_number_sid': payload.get('phone_number_sid'), - 'reason': payload.get('reason'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'to': payload.get('to'), - 'url': payload.get('url'), - 'use_case': payload.get('use_case'), - } - - # Context - self._context = None - self._solution = {} - - @property - def account_sid(self): - """ - :returns: Account Sid. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def bg_color(self): - """ - :returns: Background color of the current phone call - :rtype: unicode - """ - return self._properties['bg_color'] - - @property - def brand_sid(self): - """ - :returns: Brand Sid. - :rtype: unicode - """ - return self._properties['brand_sid'] - - @property - def branded_channel_sid(self): - """ - :returns: Branded Channel Sid. - :rtype: unicode - """ - return self._properties['branded_channel_sid'] - - @property - def business_sid(self): - """ - :returns: Business Sid. - :rtype: unicode - """ - return self._properties['business_sid'] - - @property - def call_sid(self): - """ - :returns: A string that uniquely identifies this phone call. - :rtype: unicode - """ - return self._properties['call_sid'] - - @property - def caller(self): - """ - :returns: Caller name of the current phone call - :rtype: unicode - """ - return self._properties['caller'] - - @property - def created_at(self): - """ - :returns: The date this Current Call was created - :rtype: datetime - """ - return self._properties['created_at'] - - @property - def font_color(self): - """ - :returns: Font color of the current phone call - :rtype: unicode - """ - return self._properties['font_color'] - - @property - def from_(self): - """ - :returns: The originating Phone Number - :rtype: unicode - """ - return self._properties['from_'] - - @property - def logo(self): - """ - :returns: Logo URL of the caller - :rtype: unicode - """ - return self._properties['logo'] - - @property - def phone_number_sid(self): - """ - :returns: Phone Number Sid. - :rtype: unicode - """ - return self._properties['phone_number_sid'] - - @property - def reason(self): - """ - :returns: The business reason for this phone call - :rtype: unicode - """ - return self._properties['reason'] - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this current branded phone call. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: The status of the current phone call - :rtype: unicode - """ - return self._properties['status'] - - @property - def to(self): - """ - :returns: The terminating Phone Number - :rtype: unicode - """ - return self._properties['to'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - @property - def use_case(self): - """ - :returns: The use case for the current phone call - :rtype: unicode - """ - return self._properties['use_case'] - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/preview/understand/__init__.py b/twilio/rest/preview/understand/__init__.py deleted file mode 100644 index a7f7ef6217..0000000000 --- a/twilio/rest/preview/understand/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -r""" -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 f951c05fe7..0000000000 --- a/twilio/rest/preview/understand/assistant/__init__.py +++ /dev/null @@ -1,707 +0,0 @@ -# coding=utf-8 -r""" -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.understand.assistant.assistant_fallback_actions import AssistantFallbackActionsList -from twilio.rest.preview.understand.assistant.assistant_initiation_actions import AssistantInitiationActionsList -from twilio.rest.preview.understand.assistant.dialogue import DialogueList -from twilio.rest.preview.understand.assistant.field_type import FieldTypeList -from twilio.rest.preview.understand.assistant.model_build import ModelBuildList -from twilio.rest.preview.understand.assistant.query import QueryList -from twilio.rest.preview.understand.assistant.style_sheet import StyleSheetList -from twilio.rest.preview.understand.assistant.task import TaskList - - -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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, fallback_actions=values.unset, - initiation_actions=values.unset, style_sheet=values.unset): - """ - Create the AssistantInstance - - :param unicode friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param bool log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode callback_url: A user-provided URL to send event callbacks to. - :param unicode callback_events: Space-separated list of callback events that will trigger callbacks. - :param dict fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param dict initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param dict style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The created AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'UniqueName': unique_name, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - 'FallbackActions': serialize.object(fallback_actions), - 'InitiationActions': serialize.object(initiation_actions), - 'StyleSheet': serialize.object(style_sheet), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AssistantInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a AssistantContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :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: A 34 character string that uniquely identifies this resource. - - :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: A 34 character string that uniquely identifies this resource. - - :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._tasks = None - self._model_builds = None - self._queries = None - self._assistant_fallback_actions = None - self._assistant_initiation_actions = None - self._dialogues = None - self._style_sheet = None - - def fetch(self): - """ - Fetch the AssistantInstance - - :returns: The fetched AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AssistantInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, friendly_name=values.unset, log_queries=values.unset, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, fallback_actions=values.unset, - initiation_actions=values.unset, style_sheet=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param bool log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode callback_url: A user-provided URL to send event callbacks to. - :param unicode callback_events: Space-separated list of callback events that will trigger callbacks. - :param dict fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param dict initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param dict style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'LogQueries': log_queries, - 'UniqueName': unique_name, - 'CallbackUrl': callback_url, - 'CallbackEvents': callback_events, - 'FallbackActions': serialize.object(fallback_actions), - 'InitiationActions': serialize.object(initiation_actions), - 'StyleSheet': serialize.object(style_sheet), - }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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 tasks(self): - """ - Access the tasks - - :returns: twilio.rest.preview.understand.assistant.task.TaskList - :rtype: twilio.rest.preview.understand.assistant.task.TaskList - """ - if self._tasks is None: - self._tasks = TaskList(self._version, assistant_sid=self._solution['sid'], ) - return self._tasks - - @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 - - @property - def assistant_fallback_actions(self): - """ - Access the assistant_fallback_actions - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - """ - if self._assistant_fallback_actions is None: - self._assistant_fallback_actions = AssistantFallbackActionsList( - self._version, - assistant_sid=self._solution['sid'], - ) - return self._assistant_fallback_actions - - @property - def assistant_initiation_actions(self): - """ - Access the assistant_initiation_actions - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - """ - if self._assistant_initiation_actions is None: - self._assistant_initiation_actions = AssistantInitiationActionsList( - self._version, - assistant_sid=self._solution['sid'], - ) - return self._assistant_initiation_actions - - @property - def dialogues(self): - """ - Access the dialogues - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueList - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueList - """ - if self._dialogues is None: - self._dialogues = DialogueList(self._version, assistant_sid=self._solution['sid'], ) - return self._dialogues - - @property - def style_sheet(self): - """ - Access the style_sheet - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - """ - if self._style_sheet is None: - self._style_sheet = StyleSheetList(self._version, assistant_sid=self._solution['sid'], ) - return self._style_sheet - - 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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'latest_model_build_sid': payload.get('latest_model_build_sid'), - 'links': payload.get('links'), - 'log_queries': payload.get('log_queries'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - 'callback_url': payload.get('callback_url'), - 'callback_events': payload.get('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 unique ID of the Account that created this Assistant. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :rtype: unicode - """ - return self._properties['friendly_name'] - - @property - def latest_model_build_sid(self): - """ - :returns: The unique ID (Sid) of the latest model build. Null if no model has been built. - :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: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. - :rtype: bool - """ - return self._properties['log_queries'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: A user-provided string that uniquely identifies this resource as an alternative to the sid. You can use the unique name in the URL path. Unique up to 64 characters long. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def callback_url(self): - """ - :returns: A user-provided URL to send event callbacks to. - :rtype: unicode - """ - return self._properties['callback_url'] - - @property - def callback_events(self): - """ - :returns: Space-separated list of callback events that will trigger callbacks. - :rtype: unicode - """ - return self._properties['callback_events'] - - def fetch(self): - """ - Fetch the AssistantInstance - - :returns: The fetched AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, log_queries=values.unset, - unique_name=values.unset, callback_url=values.unset, - callback_events=values.unset, fallback_actions=values.unset, - initiation_actions=values.unset, style_sheet=values.unset): - """ - Update the AssistantInstance - - :param unicode friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param bool log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode callback_url: A user-provided URL to send event callbacks to. - :param unicode callback_events: Space-separated list of callback events that will trigger callbacks. - :param dict fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param dict initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param dict style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - :rtype: twilio.rest.preview.understand.assistant.AssistantInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - fallback_actions=fallback_actions, - initiation_actions=initiation_actions, - style_sheet=style_sheet, - ) - - 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 tasks(self): - """ - Access the tasks - - :returns: twilio.rest.preview.understand.assistant.task.TaskList - :rtype: twilio.rest.preview.understand.assistant.task.TaskList - """ - return self._proxy.tasks - - @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 - - @property - def assistant_fallback_actions(self): - """ - Access the assistant_fallback_actions - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - """ - return self._proxy.assistant_fallback_actions - - @property - def assistant_initiation_actions(self): - """ - Access the assistant_initiation_actions - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - """ - return self._proxy.assistant_initiation_actions - - @property - def dialogues(self): - """ - Access the dialogues - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueList - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueList - """ - return self._proxy.dialogues - - @property - def style_sheet(self): - """ - Access the style_sheet - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - """ - return self._proxy.style_sheet - - 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/assistant_fallback_actions.py b/twilio/rest/preview/understand/assistant/assistant_fallback_actions.py deleted file mode 100644 index 2c3ad2b33f..0000000000 --- a/twilio/rest/preview/understand/assistant/assistant_fallback_actions.py +++ /dev/null @@ -1,279 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 AssistantFallbackActionsList(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 AssistantFallbackActionsList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsList - """ - super(AssistantFallbackActionsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a AssistantFallbackActionsContext - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - """ - return AssistantFallbackActionsContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __call__(self): - """ - Constructs a AssistantFallbackActionsContext - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - """ - return AssistantFallbackActionsContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantFallbackActionsPage(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 AssistantFallbackActionsPage - - :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.assistant_fallback_actions.AssistantFallbackActionsPage - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsPage - """ - super(AssistantFallbackActionsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AssistantFallbackActionsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - return AssistantFallbackActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantFallbackActionsContext(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): - """ - Initialize the AssistantFallbackActionsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - """ - super(AssistantFallbackActionsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/FallbackActions'.format(**self._solution) - - def fetch(self): - """ - Fetch the AssistantFallbackActionsInstance - - :returns: The fetched AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AssistantFallbackActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - ) - - def update(self, fallback_actions=values.unset): - """ - Update the AssistantFallbackActionsInstance - - :param dict fallback_actions: The fallback_actions - - :returns: The updated AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - data = values.of({'FallbackActions': serialize.object(fallback_actions), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return AssistantFallbackActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_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 AssistantFallbackActionsInstance(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): - """ - Initialize the AssistantFallbackActionsInstance - - :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - super(AssistantFallbackActionsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_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: AssistantFallbackActionsContext for this AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsContext - """ - if self._context is None: - self._context = AssistantFallbackActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the AssistantFallbackActionsInstance - - :returns: The fetched AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - return self._proxy.fetch() - - def update(self, fallback_actions=values.unset): - """ - Update the AssistantFallbackActionsInstance - - :param dict fallback_actions: The fallback_actions - - :returns: The updated AssistantFallbackActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance - """ - return self._proxy.update(fallback_actions=fallback_actions, ) - - 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/assistant_initiation_actions.py b/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py deleted file mode 100644 index a0ffd23431..0000000000 --- a/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py +++ /dev/null @@ -1,285 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 AssistantInitiationActionsList(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 AssistantInitiationActionsList - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsList - """ - super(AssistantInitiationActionsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a AssistantInitiationActionsContext - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - """ - return AssistantInitiationActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - ) - - def __call__(self): - """ - Constructs a AssistantInitiationActionsContext - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - """ - return AssistantInitiationActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantInitiationActionsPage(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 AssistantInitiationActionsPage - - :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.assistant_initiation_actions.AssistantInitiationActionsPage - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsPage - """ - super(AssistantInitiationActionsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of AssistantInitiationActionsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - return AssistantInitiationActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class AssistantInitiationActionsContext(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): - """ - Initialize the AssistantInitiationActionsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - """ - super(AssistantInitiationActionsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/InitiationActions'.format(**self._solution) - - def fetch(self): - """ - Fetch the AssistantInitiationActionsInstance - - :returns: The fetched AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return AssistantInitiationActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - ) - - def update(self, initiation_actions=values.unset): - """ - Update the AssistantInitiationActionsInstance - - :param dict initiation_actions: The initiation_actions - - :returns: The updated AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - data = values.of({'InitiationActions': serialize.object(initiation_actions), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return AssistantInitiationActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_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 AssistantInitiationActionsInstance(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): - """ - Initialize the AssistantInitiationActionsInstance - - :returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - super(AssistantInitiationActionsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_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: AssistantInitiationActionsContext for this AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsContext - """ - if self._context is None: - self._context = AssistantInitiationActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The account_sid - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The assistant_sid - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the AssistantInitiationActionsInstance - - :returns: The fetched AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - return self._proxy.fetch() - - def update(self, initiation_actions=values.unset): - """ - Update the AssistantInitiationActionsInstance - - :param dict initiation_actions: The initiation_actions - - :returns: The updated AssistantInitiationActionsInstance - :rtype: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance - """ - return self._proxy.update(initiation_actions=initiation_actions, ) - - 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/dialogue.py b/twilio/rest/preview/understand/assistant/dialogue.py deleted file mode 100644 index 5f33372693..0000000000 --- a/twilio/rest/preview/understand/assistant/dialogue.py +++ /dev/null @@ -1,260 +0,0 @@ -# coding=utf-8 -r""" -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 DialogueList(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 DialogueList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueList - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueList - """ - super(DialogueList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self, sid): - """ - Constructs a DialogueContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - """ - return DialogueContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a DialogueContext - - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - """ - return DialogueContext(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 DialoguePage(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 DialoguePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The unique ID of the parent Assistant. - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialoguePage - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialoguePage - """ - super(DialoguePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DialogueInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - """ - return DialogueInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DialogueContext(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 DialogueContext - - :param Version version: Version that contains the resource - :param assistant_sid: The assistant_sid - :param sid: The sid - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - """ - super(DialogueContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Dialogues/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the DialogueInstance - - :returns: The fetched DialogueInstance - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_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 DialogueInstance(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 DialogueInstance - - :returns: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - """ - super(DialogueInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'data': payload.get('data'), - 'url': payload.get('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: DialogueContext for this DialogueInstance - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueContext - """ - if self._context is None: - self._context = DialogueContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Field. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: The unique ID of the Dialogue - :rtype: unicode - """ - return self._properties['sid'] - - @property - def data(self): - """ - :returns: The dialogue memory object as json - :rtype: dict - """ - return self._properties['data'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the DialogueInstance - - :returns: The fetched DialogueInstance - :rtype: twilio.rest.preview.understand.assistant.dialogue.DialogueInstance - """ - 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/understand/assistant/field_type/__init__.py b/twilio/rest/preview/understand/assistant/field_type/__init__.py deleted file mode 100644 index 4980ff0107..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/__init__.py +++ /dev/null @@ -1,472 +0,0 @@ -# coding=utf-8 -r""" -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 unique ID of the Assistant. - - :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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the FieldTypeInstance - - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - - :returns: The created FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=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 unique ID of the Assistant. - - :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 the FieldTypeInstance - - :returns: The fetched FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The updated FieldTypeInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance - """ - data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'links': payload.get('links'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('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 unique ID of the Account that created this Field Type. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :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 unique ID of the Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FieldTypeInstance - - :returns: The 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: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The 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 5f8b8b9e14..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/field_value.py +++ /dev/null @@ -1,456 +0,0 @@ -# coding=utf-8 -r""" -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 unique ID of the Assistant. - :param field_type_sid: The unique ID of the Field Type associated with this Field Value. - - :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: An ISO language-country string of the value. For example: en-US - :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']) - - 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: An ISO language-country string of the value. For example: en-US - :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: An ISO language-country string of the value. For example: en-US - :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 - """ - data = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the FieldValueInstance - - :param unicode language: An ISO language-country string of the value. - :param unicode value: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode synonym_of: A value that indicates this field value is a synonym of. Empty if the value is not a synonym. - - :returns: The 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(method='POST', uri=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 unique ID of the Assistant. - :param field_type_sid: The unique ID of the Field Type associated with this Field Value. - - :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 the FieldValueInstance - - :returns: The fetched FieldValueInstance - :rtype: twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'field_type_sid': payload.get('field_type_sid'), - 'language': payload.get('language'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'value': payload.get('value'), - 'url': payload.get('url'), - 'synonym_of': payload.get('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 unique ID of the Account that created this Field Value. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type_sid(self): - """ - :returns: The unique ID of the Field Type associated with this Field Value. - :rtype: unicode - """ - return self._properties['field_type_sid'] - - @property - def language(self): - """ - :returns: An ISO language-country string of the value. - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def value(self): - """ - :returns: The Field Value itself. - :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: A value that indicates this field value is a synonym of. Empty if the value is not a synonym. - :rtype: unicode - """ - return self._properties['synonym_of'] - - def fetch(self): - """ - Fetch the FieldValueInstance - - :returns: The 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/model_build.py b/twilio/rest/preview/understand/assistant/model_build.py deleted file mode 100644 index 974356359a..0000000000 --- a/twilio/rest/preview/understand/assistant/model_build.py +++ /dev/null @@ -1,456 +0,0 @@ -# coding=utf-8 -r""" -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 unique ID of the parent Assistant. - - :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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 the ModelBuildInstance - - :param unicode status_callback: The status_callback - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The created ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - data = values.of({'StatusCallback': status_callback, 'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=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 unique ID of the parent Assistant. - - :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 the ModelBuildInstance - - :returns: The fetched ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The updated ModelBuildInstance - :rtype: twilio.rest.preview.understand.assistant.model_build.ModelBuildInstance - """ - data = values.of({'UniqueName': unique_name, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - 'build_duration': deserialize.integer(payload.get('build_duration')), - 'error_code': deserialize.integer(payload.get('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 unique ID of the Account that created this Model Build. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: A string that described the model build status. The values can be: enqueued, building, completed, failed - :rtype: ModelBuildInstance.Status - """ - return self._properties['status'] - - @property - def unique_name(self): - """ - :returns: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :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 time in seconds it took to build the model. - :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 the ModelBuildInstance - - :returns: The 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: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The 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 1400f61e48..0000000000 --- a/twilio/rest/preview/understand/assistant/query.py +++ /dev/null @@ -1,518 +0,0 @@ -# coding=utf-8 -r""" -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 unique ID of the parent Assistant. - - :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: An ISO language-country string of the sample. - :param unicode model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :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']) - - 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: An ISO language-country string of the sample. - :param unicode model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :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: An ISO language-country string of the sample. - :param unicode model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :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 - """ - data = values.of({ - 'Language': language, - 'ModelBuild': model_build, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, tasks=values.unset, model_build=values.unset, - field=values.unset): - """ - Create the QueryInstance - - :param unicode language: An ISO language-country string of the sample. - :param unicode query: A user-provided string that uniquely identifies this resource as an alternative to the sid. It can be up to 2048 characters long. - :param unicode tasks: Constraints the query to a set of tasks. Useful when you need to constrain the paths the user can take. Tasks should be comma separated task-unique-name-1, task-unique-name-2 - :param unicode model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param unicode field: Constraints the query to a given Field with an task. Useful when you know the Field you are expecting. It accepts one field in the format task-unique-name-1:field-unique-name - - :returns: The created QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - data = values.of({ - 'Language': language, - 'Query': query, - 'Tasks': tasks, - 'ModelBuild': model_build, - 'Field': field, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return QueryInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a QueryContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :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: A 34 character string that uniquely identifies this resource. - - :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 unique ID of the parent Assistant. - - :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 unique ID of the Assistant. - :param sid: A 34 character string that uniquely identifies this resource. - - :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 the QueryInstance - - :returns: The fetched QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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: An optional reference to the Sample created from this query. - :param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The updated QueryInstance - :rtype: twilio.rest.preview.understand.assistant.query.QueryInstance - """ - data = values.of({'SampleSid': sample_sid, 'Status': status, }) - - payload = self._version.update(method='POST', uri=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(method='DELETE', uri=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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'results': payload.get('results'), - 'language': payload.get('language'), - 'model_build_sid': payload.get('model_build_sid'), - 'query': payload.get('query'), - 'sample_sid': payload.get('sample_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'status': payload.get('status'), - 'url': payload.get('url'), - 'source_channel': payload.get('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 unique ID of the Account that created this Query. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def results(self): - """ - :returns: The natural language analysis results which include the Task recognized, the confidence score and a list of identified Fields. - :rtype: dict - """ - return self._properties['results'] - - @property - def language(self): - """ - :returns: An ISO language-country string of the sample. - :rtype: unicode - """ - return self._properties['language'] - - @property - def model_build_sid(self): - """ - :returns: The unique ID of the Model Build queried. - :rtype: unicode - """ - return self._properties['model_build_sid'] - - @property - def query(self): - """ - :returns: The end-user's natural language input. - :rtype: unicode - """ - return self._properties['query'] - - @property - def sample_sid(self): - """ - :returns: An optional reference to the Sample created from this query. - :rtype: unicode - """ - return self._properties['sample_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def status(self): - """ - :returns: A string that described the query status. The values can be: pending_review, reviewed, discarded - :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 communication channel where this end-user input came from - :rtype: unicode - """ - return self._properties['source_channel'] - - def fetch(self): - """ - Fetch the QueryInstance - - :returns: The 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: An optional reference to the Sample created from this query. - :param unicode status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The 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/understand/assistant/style_sheet.py b/twilio/rest/preview/understand/assistant/style_sheet.py deleted file mode 100644 index 26813c8151..0000000000 --- a/twilio/rest/preview/understand/assistant/style_sheet.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 StyleSheetList(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 StyleSheetList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetList - """ - super(StyleSheetList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - - def get(self): - """ - Constructs a StyleSheetContext - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - """ - return StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __call__(self): - """ - Constructs a StyleSheetContext - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - """ - return StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StyleSheetPage(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 StyleSheetPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The unique ID of the Assistant - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetPage - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetPage - """ - super(StyleSheetPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of StyleSheetInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class StyleSheetContext(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): - """ - Initialize the StyleSheetContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - """ - super(StyleSheetContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/StyleSheet'.format(**self._solution) - - def fetch(self): - """ - Fetch the StyleSheetInstance - - :returns: The fetched StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def update(self, style_sheet=values.unset): - """ - Update the StyleSheetInstance - - :param dict style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - data = values.of({'StyleSheet': serialize.object(style_sheet), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return StyleSheetInstance(self._version, payload, assistant_sid=self._solution['assistant_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 StyleSheetInstance(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): - """ - Initialize the StyleSheetInstance - - :returns: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - super(StyleSheetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_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: StyleSheetContext for this StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetContext - """ - if self._context is None: - self._context = StyleSheetContext(self._version, assistant_sid=self._solution['assistant_sid'], ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Assistant - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the Assistant - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The JSON style sheet object - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the StyleSheetInstance - - :returns: The fetched StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - return self._proxy.fetch() - - def update(self, style_sheet=values.unset): - """ - Update the StyleSheetInstance - - :param dict style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - :rtype: twilio.rest.preview.understand.assistant.style_sheet.StyleSheetInstance - """ - return self._proxy.update(style_sheet=style_sheet, ) - - 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/task/__init__.py b/twilio/rest/preview/understand/assistant/task/__init__.py deleted file mode 100644 index 9aac68ff08..0000000000 --- a/twilio/rest/preview/understand/assistant/task/__init__.py +++ /dev/null @@ -1,590 +0,0 @@ -# coding=utf-8 -r""" -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.understand.assistant.task.field import FieldList -from twilio.rest.preview.understand.assistant.task.sample import SampleList -from twilio.rest.preview.understand.assistant.task.task_actions import TaskActionsList -from twilio.rest.preview.understand.assistant.task.task_statistics import TaskStatisticsList - - -class TaskList(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 TaskList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - - :returns: twilio.rest.preview.understand.assistant.task.TaskList - :rtype: twilio.rest.preview.understand.assistant.task.TaskList - """ - super(TaskList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks'.format(**self._solution) - - def stream(self, 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 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.task.TaskInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.task.TaskInstance] - """ - 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 TaskInstance 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 TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return TaskPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return TaskPage(self._version, response, self._solution) - - def create(self, unique_name, friendly_name=values.unset, actions=values.unset, - actions_url=values.unset): - """ - Create the TaskInstance - - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param unicode friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param dict actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param unicode actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The created TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'Actions': serialize.object(actions), - 'ActionsUrl': actions_url, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return TaskInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def get(self, sid): - """ - Constructs a TaskContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.TaskContext - :rtype: twilio.rest.preview.understand.assistant.task.TaskContext - """ - return TaskContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a TaskContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.TaskContext - :rtype: twilio.rest.preview.understand.assistant.task.TaskContext - """ - return TaskContext(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 TaskPage(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 TaskPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The unique ID of the Assistant. - - :returns: twilio.rest.preview.understand.assistant.task.TaskPage - :rtype: twilio.rest.preview.understand.assistant.task.TaskPage - """ - super(TaskPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.task.TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - return TaskInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskContext(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 TaskContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.TaskContext - :rtype: twilio.rest.preview.understand.assistant.task.TaskContext - """ - super(TaskContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{sid}'.format(**self._solution) - - # Dependents - self._fields = None - self._samples = None - self._task_actions = None - self._statistics = None - - def fetch(self): - """ - Fetch the TaskInstance - - :returns: The fetched TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def update(self, friendly_name=values.unset, unique_name=values.unset, - actions=values.unset, actions_url=values.unset): - """ - Update the TaskInstance - - :param unicode friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param dict actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param unicode actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'Actions': serialize.object(actions), - 'ActionsUrl': actions_url, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the TaskInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - - @property - def fields(self): - """ - Access the fields - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldList - """ - if self._fields is None: - self._fields = FieldList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleList - """ - if self._samples is None: - self._samples = SampleList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._samples - - @property - def task_actions(self): - """ - Access the task_actions - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - """ - if self._task_actions is None: - self._task_actions = TaskActionsList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._task_actions - - @property - def statistics(self): - """ - Access the statistics - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - """ - if self._statistics is None: - self._statistics = TaskStatisticsList( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['sid'], - ) - return self._statistics - - 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 TaskInstance(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 TaskInstance - - :returns: twilio.rest.preview.understand.assistant.task.TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - super(TaskInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'links': payload.get('links'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'actions_url': payload.get('actions_url'), - 'url': payload.get('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: TaskContext for this TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskContext - """ - if self._context is None: - self._context = TaskContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Task. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def friendly_name(self): - """ - :returns: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :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 unique ID of the Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def actions_url(self): - """ - :returns: User-provided HTTP endpoint where from the assistant fetches actions - :rtype: unicode - """ - return self._properties['actions_url'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the TaskInstance - - :returns: The fetched TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - return self._proxy.fetch() - - def update(self, friendly_name=values.unset, unique_name=values.unset, - actions=values.unset, actions_url=values.unset): - """ - Update the TaskInstance - - :param unicode friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param dict actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param unicode actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - :rtype: twilio.rest.preview.understand.assistant.task.TaskInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - def delete(self): - """ - Deletes the TaskInstance - - :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.task.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldList - """ - return self._proxy.fields - - @property - def samples(self): - """ - Access the samples - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleList - """ - return self._proxy.samples - - @property - def task_actions(self): - """ - Access the task_actions - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - """ - return self._proxy.task_actions - - @property - def statistics(self): - """ - Access the statistics - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - """ - return self._proxy.statistics - - 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/task/field.py b/twilio/rest/preview/understand/assistant/task/field.py deleted file mode 100644 index 31cf2a0156..0000000000 --- a/twilio/rest/preview/understand/assistant/task/field.py +++ /dev/null @@ -1,438 +0,0 @@ -# coding=utf-8 -r""" -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, task_sid): - """ - Initialize the FieldList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldList - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldList - """ - super(FieldList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_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.task.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']) - - 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.task.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.task.field.FieldPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.task.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 the FieldInstance - - :param unicode field_type: The unique name or sid of the FieldType. It can be any Built-in Field Type or the unique_name or sid of a custom Field Type. - :param unicode unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The created FieldInstance - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldInstance - """ - data = values.of({'FieldType': field_type, 'UniqueName': unique_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def get(self, sid): - """ - Constructs a FieldContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a FieldContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldContext - """ - return FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldPage - :rtype: twilio.rest.preview.understand.assistant.task.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.task.field.FieldInstance - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldInstance - """ - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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, task_sid, sid): - """ - Initialize the FieldContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldContext - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldContext - """ - super(FieldContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the FieldInstance - - :returns: The fetched FieldInstance - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the FieldInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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, task_sid, sid=None): - """ - Initialize the FieldInstance - - :returns: twilio.rest.preview.understand.assistant.task.field.FieldInstance - :rtype: twilio.rest.preview.understand.assistant.task.field.FieldInstance - """ - super(FieldInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'field_type': payload.get('field_type'), - 'task_sid': payload.get('task_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'task_sid': task_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.task.field.FieldContext - """ - if self._context is None: - self._context = FieldContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Field. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def field_type(self): - """ - :returns: The Field Type of this field. It can be any Built-in Field Type or unique_name or the Field Type sid of a custom Field Type. - :rtype: unicode - """ - return self._properties['field_type'] - - @property - def task_sid(self): - """ - :returns: The unique ID of the Task associated with this Field. - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FieldInstance - - :returns: The fetched FieldInstance - :rtype: twilio.rest.preview.understand.assistant.task.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/task/sample.py b/twilio/rest/preview/understand/assistant/task/sample.py deleted file mode 100644 index f3c1d0f938..0000000000 --- a/twilio/rest/preview/understand/assistant/task/sample.py +++ /dev/null @@ -1,494 +0,0 @@ -# coding=utf-8 -r""" -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, task_sid): - """ - Initialize the SampleList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Sample. - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleList - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleList - """ - super(SampleList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_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: An ISO language-country string of the sample. - :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.task.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']) - - 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: An ISO language-country string of the sample. - :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.task.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: An ISO language-country string of the sample. - :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.task.sample.SamplePage - """ - data = values.of({ - 'Language': language, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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.task.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 the SampleInstance - - :param unicode language: An ISO language-country string of the sample. - :param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null - - :returns: The created SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def get(self, sid): - """ - Constructs a SampleContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a SampleContext - - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext - """ - return SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Sample. - - :returns: twilio.rest.preview.understand.assistant.task.sample.SamplePage - :rtype: twilio.rest.preview.understand.assistant.task.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.task.sample.SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - """ - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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, task_sid, sid): - """ - Initialize the SampleContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Sample. - :param sid: A 34 character string that uniquely identifies this resource. - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleContext - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleContext - """ - super(SampleContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, 'sid': sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the SampleInstance - - :returns: The fetched SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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: An ISO language-country string of the sample. - :param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null - - :returns: The updated SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - """ - data = values.of({'Language': language, 'TaggedText': tagged_text, 'SourceChannel': source_channel, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the SampleInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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, task_sid, sid=None): - """ - Initialize the SampleInstance - - :returns: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.sample.SampleInstance - """ - super(SampleInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'task_sid': payload.get('task_sid'), - 'language': payload.get('language'), - 'assistant_sid': payload.get('assistant_sid'), - 'sid': payload.get('sid'), - 'tagged_text': payload.get('tagged_text'), - 'url': payload.get('url'), - 'source_channel': payload.get('source_channel'), - } - - # Context - self._context = None - self._solution = { - 'assistant_sid': assistant_sid, - 'task_sid': task_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.task.sample.SampleContext - """ - if self._context is None: - self._context = SampleContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Sample. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def date_created(self): - """ - :returns: The date that this resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date that this resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def task_sid(self): - """ - :returns: The unique ID of the Task associated with this Sample. - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def language(self): - """ - :returns: An ISO language-country string of the sample. - :rtype: unicode - """ - return self._properties['language'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def sid(self): - """ - :returns: A 34 character string that uniquely identifies this resource. - :rtype: unicode - """ - return self._properties['sid'] - - @property - def tagged_text(self): - """ - :returns: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :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 communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null - :rtype: unicode - """ - return self._properties['source_channel'] - - def fetch(self): - """ - Fetch the SampleInstance - - :returns: The fetched SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.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: An ISO language-country string of the sample. - :param unicode tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param unicode source_channel: The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null - - :returns: The updated SampleInstance - :rtype: twilio.rest.preview.understand.assistant.task.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/task/task_actions.py b/twilio/rest/preview/understand/assistant/task/task_actions.py deleted file mode 100644 index d27aae5c81..0000000000 --- a/twilio/rest/preview/understand/assistant/task/task_actions.py +++ /dev/null @@ -1,303 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 TaskActionsList(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, task_sid): - """ - Initialize the TaskActionsList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task. - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsList - """ - super(TaskActionsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - - def get(self): - """ - Constructs a TaskActionsContext - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __call__(self): - """ - Constructs a TaskActionsContext - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskActionsPage(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 TaskActionsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task. - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsPage - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsPage - """ - super(TaskActionsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskActionsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskActionsContext(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, task_sid): - """ - Initialize the TaskActionsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task. - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - """ - super(TaskActionsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Actions'.format(**self._solution) - - def fetch(self): - """ - Fetch the TaskActionsInstance - - :returns: The fetched TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def update(self, actions=values.unset): - """ - Update the TaskActionsInstance - - :param dict actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - data = values.of({'Actions': serialize.object(actions), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 TaskActionsInstance(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, task_sid): - """ - Initialize the TaskActionsInstance - - :returns: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - super(TaskActionsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'task_sid': payload.get('task_sid'), - 'url': payload.get('url'), - 'data': payload.get('data'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_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: TaskActionsContext for this TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsContext - """ - if self._context is None: - self._context = TaskActionsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Field. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def task_sid(self): - """ - :returns: The unique ID of the Task. - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - @property - def data(self): - """ - :returns: The data - :rtype: dict - """ - return self._properties['data'] - - def fetch(self): - """ - Fetch the TaskActionsInstance - - :returns: The fetched TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - return self._proxy.fetch() - - def update(self, actions=values.unset): - """ - Update the TaskActionsInstance - - :param dict actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_actions.TaskActionsInstance - """ - return self._proxy.update(actions=actions, ) - - 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/task/task_statistics.py b/twilio/rest/preview/understand/assistant/task/task_statistics.py deleted file mode 100644 index 6f7f505908..0000000000 --- a/twilio/rest/preview/understand/assistant/task/task_statistics.py +++ /dev/null @@ -1,281 +0,0 @@ -# coding=utf-8 -r""" -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 TaskStatisticsList(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, task_sid): - """ - Initialize the TaskStatisticsList - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsList - """ - super(TaskStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - - def get(self): - """ - Constructs a TaskStatisticsContext - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __call__(self): - """ - Constructs a TaskStatisticsContext - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskStatisticsPage(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 TaskStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsPage - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsPage - """ - super(TaskStatisticsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of TaskStatisticsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - """ - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskStatisticsContext(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, task_sid): - """ - Initialize the TaskStatisticsContext - - :param Version version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - """ - super(TaskStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_sid, } - self._uri = '/Assistants/{assistant_sid}/Tasks/{task_sid}/Statistics'.format(**self._solution) - - def fetch(self): - """ - Fetch the TaskStatisticsInstance - - :returns: The fetched TaskStatisticsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_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 TaskStatisticsInstance(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, task_sid): - """ - Initialize the TaskStatisticsInstance - - :returns: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - """ - super(TaskStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'assistant_sid': payload.get('assistant_sid'), - 'task_sid': payload.get('task_sid'), - 'samples_count': deserialize.integer(payload.get('samples_count')), - 'fields_count': deserialize.integer(payload.get('fields_count')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'assistant_sid': assistant_sid, 'task_sid': task_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: TaskStatisticsContext for this TaskStatisticsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsContext - """ - if self._context is None: - self._context = TaskStatisticsContext( - self._version, - assistant_sid=self._solution['assistant_sid'], - task_sid=self._solution['task_sid'], - ) - return self._context - - @property - def account_sid(self): - """ - :returns: The unique ID of the Account that created this Field. - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def assistant_sid(self): - """ - :returns: The unique ID of the parent Assistant. - :rtype: unicode - """ - return self._properties['assistant_sid'] - - @property - def task_sid(self): - """ - :returns: The unique ID of the Task associated with this Field. - :rtype: unicode - """ - return self._properties['task_sid'] - - @property - def samples_count(self): - """ - :returns: The total number of Samples associated with this Task. - :rtype: unicode - """ - return self._properties['samples_count'] - - @property - def fields_count(self): - """ - :returns: The total number of Fields associated with this Task. - :rtype: unicode - """ - return self._properties['fields_count'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the TaskStatisticsInstance - - :returns: The fetched TaskStatisticsInstance - :rtype: twilio.rest.preview.understand.assistant.task.task_statistics.TaskStatisticsInstance - """ - 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/wireless/__init__.py b/twilio/rest/preview/wireless/__init__.py index 97442a024e..85ed4fb54d 100644 --- a/twilio/rest/preview/wireless/__init__.py +++ b/twilio/rest/preview/wireless/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 9ba70d7baa..8e715e09ef 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -1,448 +1,595 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 - - :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 + Provide a friendly representation - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage + :returns: Machine friendly representation """ - data = values.of({ - 'Device': device, - 'Sim': sim, - 'Status': status, - 'Direction': direction, - '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(method='GET', uri=self._uri, params=data, ) - return CommandPage(self._version, response, self._solution) +class CommandContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, sid: str): """ - Retrieve a specific page of CommandInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the CommandContext - :returns: Page of CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandPage + :param version: Version that contains the resource + :param sid: """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return CommandPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**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): + def fetch(self) -> CommandInstance: """ - Create the CommandInstance + Fetch the 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 - :returns: The created CommandInstance - :rtype: twilio.rest.preview.wireless.command.CommandInstance + :returns: The fetched CommandInstance """ - data = values.of({ - 'Command': command, - 'Device': device, - 'Sim': sim, - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - 'CommandMode': command_mode, - 'IncludeSid': include_sid, - }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return CommandInstance(self._version, payload, ) + headers["Accept"] = "application/json" - def get(self, sid): - """ - Constructs a CommandContext + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :param sid: The sid + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext + async def fetch_async(self) -> CommandInstance: """ - return CommandContext(self._version, sid=sid, ) + Asynchronous coroutine to fetch the CommandInstance - def __call__(self, sid): + + :returns: The fetched CommandInstance """ - Constructs a CommandContext - :param sid: The sid + headers = values.of({}) - :returns: twilio.rest.preview.wireless.command.CommandContext - :rtype: twilio.rest.preview.wireless.command.CommandContext - """ - return CommandContext(self._version, sid=sid, ) + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __repr__(self): + 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 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 the CommandInstance + Create the CommandInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return CommandInstance(self._version, payload, sid=self._solution['sid'], ) + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __repr__(self): - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - :rtype: str + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'device_sid': payload.get('device_sid'), - 'sim_sid': payload.get('sim_sid'), - 'command': payload.get('command'), - 'command_mode': payload.get('command_mode'), - 'status': payload.get('status'), - 'direction': payload.get('direction'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 the CommandInstance + Constructs a CommandContext - :returns: The 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 d61786f85d..95e45f1ef2 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -1,495 +1,699 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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. """ +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") - def __init__(self, version): + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None + + @property + def _proxy(self) -> "RatePlanContext": """ - Initialize the RatePlanList + 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: RatePlanContext for this RatePlanInstance + """ + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanList - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanList + def delete(self) -> bool: """ - super(RatePlanList, self).__init__(version) + Deletes the RatePlanInstance - # Path Solution - self._solution = {} - self._uri = '/RatePlans'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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) + return self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.rate_plan.RatePlanInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the RatePlanInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "RatePlanInstance": """ - Lists RatePlanInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Fetch 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: The fetched RatePlanInstance """ - 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) -> "RatePlanInstance": """ - Retrieve a single page of RatePlanInstance records from the API. - Request is executed immediately + Asynchronous coroutine to 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RatePlanPage(self._version, response, self._solution) - - def get_page(self, target_url): + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Retrieve a specific page of RatePlanInstance records from the API. - Request is executed immediately + Update the RatePlanInstance - :param str target_url: API-generated URL for the requested results page + :param unique_name: + :param friendly_name: - :returns: Page of RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :returns: The updated RatePlanInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, ) - 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): + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": """ - Create the RatePlanInstance + Asynchronous coroutine to update the 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 + :param unique_name: + :param friendly_name: - :returns: The created RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance + :returns: The updated 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), - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) - return RatePlanInstance(self._version, payload, ) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a RatePlanContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The sid - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext +class RatePlanContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return RatePlanContext(self._version, sid=sid, ) + Initialize the RatePlanContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: """ - Constructs a RatePlanContext + super().__init__(version) - :param sid: The sid + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanContext - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanContext + def delete(self) -> bool: """ - return RatePlanContext(self._version, sid=sid, ) + Deletes the RatePlanInstance - 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 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. """ + 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 RatePlanPage + Asynchronous coroutine that deletes the RatePlanInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.preview.wireless.rate_plan.RatePlanPage - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanPage + :returns: True if delete succeeds, False otherwise """ - super(RatePlanPage, 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) -> RatePlanInstance: """ - Build an instance of RatePlanInstance + Fetch 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: The fetched RatePlanInstance """ - return RatePlanInstance(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 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 RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> RatePlanInstance: """ - Initialize the RatePlanContext + Asynchronous coroutine to 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({}) - def fetch(self): - """ - Fetch the RatePlanInstance + headers["Accept"] = "application/json" - :returns: The fetched RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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: The updated RatePlanInstance - :rtype: twilio.rest.preview.wireless.rate_plan.RatePlanInstance """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - 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(method='DELETE', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'data_enabled': payload.get('data_enabled'), - 'data_metering': payload.get('data_metering'), - 'data_limit': deserialize.integer(payload.get('data_limit')), - 'messaging_enabled': payload.get('messaging_enabled'), - 'voice_enabled': payload.get('voice_enabled'), - 'national_roaming_enabled': payload.get('national_roaming_enabled'), - 'international_roaming': payload.get('international_roaming'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 - @property - def data_limit(self): """ - :returns: The data_limit - :rtype: unicode + 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: """ - return self._properties['data_limit'] + Create the RatePlanInstance - @property - def messaging_enabled(self): + :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 """ - :returns: The messaging_enabled - :rtype: bool + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance """ - return self._properties['messaging_enabled'] - @property - def voice_enabled(self): + 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of RatePlanInstance """ - Fetch the RatePlanInstance + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) - :returns: The 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: The 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 f5281444e5..07a9e74da0 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -1,657 +1,833 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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) +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") - # 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 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) + 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 """ - 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']) + 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 fetch(self) -> "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. + Fetch the SimInstance - :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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.preview.wireless.sim.SimInstance] + :returns: The fetched 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, - )) + return self._proxy.fetch() - 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 fetch_async(self) -> "SimInstance": """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SimInstance - :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 - :returns: Page of SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimPage + :returns: The fetched SimInstance """ - data = values.of({ - 'Status': status, - 'Iccid': iccid, - 'RatePlan': rate_plan, - 'EId': e_id, - 'SimRegistrationCode': sim_registration_code, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SimPage(self._version, response, self._solution) - - def get_page(self, target_url): + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": """ - Retrieve a specific page of SimInstance records from the API. - Request is executed immediately + Update the SimInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimPage + :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, ) - return SimPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a SimContext - - :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: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + :returns: The updated SimInstance """ - return SimContext(self._version, sid=sid, ) + 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, + ) - def __call__(self, sid): + @property + def usage(self) -> UsageList: """ - Constructs a SimContext - - :param sid: The sid - - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.sim.SimContext + 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 + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) - def get_instance(self, payload): + self._usage: Optional[UsageList] = None + + def fetch(self) -> SimInstance: """ - Build an instance of SimInstance + Fetch the SimInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.preview.wireless.sim.SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + :returns: The fetched SimInstance """ - return SimInstance(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 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. """ + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> SimInstance: """ - Initialize the SimContext + Asynchronous coroutine to fetch the SimInstance - :param Version version: Version that contains the resource - :param sid: The sid - :returns: twilio.rest.preview.wireless.sim.SimContext - :rtype: twilio.rest.preview.wireless.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({}) - # Dependents - self._usage = None + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the SimInstance + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: The fetched SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Update the SimInstance - return SimInstance(self._version, payload, sid=self._solution['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: - 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): + :returns: The updated 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 + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: :returns: The updated SimInstance - :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, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SimInstance(self._version, payload, sid=self._solution['sid'], ) + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) @property - def usage(self): + 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'rate_plan_sid': payload.get('rate_plan_sid'), - 'friendly_name': payload.get('friendly_name'), - 'iccid': payload.get('iccid'), - 'e_id': payload.get('e_id'), - 'status': payload.get('status'), - 'commands_callback_url': payload.get('commands_callback_url'), - 'commands_callback_method': payload.get('commands_callback_method'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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): + 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: 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): - """ - :returns: The url - :rtype: unicode + :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 = 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 """ - :returns: The links - :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 = 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: """ - return self._properties['links'] + Retrieve a specific page of SimInstance 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 SimInstance """ - Fetch the SimInstance + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) - :returns: The fetched SimInstance - :rtype: twilio.rest.preview.wireless.sim.SimInstance + async def get_page_async(self, target_url: str) -> SimPage: """ - return self._proxy.fetch() + 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 - 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): + :returns: Page of SimInstance """ - Update the SimInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) - :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 + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext - :returns: The 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 a101618797..aff3731b51 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -1,290 +1,249 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 - - -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. """ - - def __init__(self, version, sim_sid): - """ - Initialize the UsageList - - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid +from twilio.base.version import Version - :returns: twilio.rest.preview.wireless.sim.usage.UsageList - :rtype: twilio.rest.preview.wireless.sim.usage.UsageList - """ - super(UsageList, self).__init__(version) - - # Path Solution - self._solution = {'sim_sid': sim_sid, } - def get(self): - """ - Constructs a UsageContext - - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext - """ - return UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) - - def __call__(self): - """ - Constructs a UsageContext - - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext - """ - return UsageContext(self._version, sim_sid=self._solution['sim_sid'], ) +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 __repr__(self): + @property + def _proxy(self) -> "UsageContext": """ - Provide a 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 - :returns: Machine friendly representation - :rtype: str + :returns: UsageContext for this UsageInstance """ - return '' - - -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. """ + if self._context is None: + self._context = UsageContext( + self._version, + sim_sid=self._solution["sim_sid"], + ) + return self._context - def __init__(self, version, response, solution): + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - Initialize the UsagePage + Fetch the UsageInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sim_sid: The sim_sid + :param end: + :param start: - :returns: twilio.rest.preview.wireless.sim.usage.UsagePage - :rtype: twilio.rest.preview.wireless.sim.usage.UsagePage + :returns: The fetched UsageInstance """ - super(UsagePage, self).__init__(version, response) + return self._proxy.fetch( + end=end, + start=start, + ) - # Path Solution - self._solution = solution - - def get_instance(self, payload): + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": """ - Build an instance of UsageInstance + Asynchronous coroutine to fetch the UsageInstance - :param dict payload: Payload response from the API + :param end: + :param start: - :returns: twilio.rest.preview.wireless.sim.usage.UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance + :returns: The fetched UsageInstance """ - return UsageInstance(self._version, payload, 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 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. """ - def __init__(self, version, sim_sid): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageContext - :param Version version: Version that contains the resource - :param sim_sid: The sim_sid - - :returns: twilio.rest.preview.wireless.sim.usage.UsageContext - :rtype: twilio.rest.preview.wireless.sim.usage.UsageContext + :param version: Version that contains the resource + :param sim_sid: """ - super(UsageContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/Usage'.format(**self._solution) + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/Usage".format(**self._solution) - def fetch(self, end=values.unset, start=values.unset): + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: """ Fetch the UsageInstance - :param unicode end: The end - :param unicode start: The start + :param end: + :param start: :returns: The fetched UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance """ - data = values.of({'End': end, 'Start': start, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + data = values.of( + { + "End": end, + "Start": start, + } + ) - return UsageInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + headers = values.of({}) - 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.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) -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): + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: """ - Initialize the UsageInstance + Asynchronous coroutine to fetch the UsageInstance - :returns: twilio.rest.preview.wireless.sim.usage.UsageInstance - :rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance + :param end: + :param start: + + :returns: The fetched UsageInstance """ - super(UsageInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sim_sid': payload.get('sim_sid'), - 'sim_unique_name': payload.get('sim_unique_name'), - 'account_sid': payload.get('account_sid'), - 'period': payload.get('period'), - 'commands_usage': payload.get('commands_usage'), - 'commands_costs': payload.get('commands_costs'), - 'data_usage': payload.get('data_usage'), - 'data_costs': payload.get('data_costs'), - 'url': payload.get('url'), - } - # Context - self._context = None - self._solution = {'sim_sid': sim_sid, } + data = values.of( + { + "End": end, + "Start": start, + } + ) - @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 = values.of({}) - :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 + headers["Accept"] = "application/json" - @property - def sim_sid(self): - """ - :returns: The sim_sid - :rtype: unicode - """ - return self._properties['sim_sid'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def sim_unique_name(self): - """ - :returns: The sim_unique_name - :rtype: unicode - """ - return self._properties['sim_unique_name'] + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_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 period(self): - """ - :returns: The period - :rtype: dict + :returns: Machine friendly representation """ - return self._properties['period'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def commands_usage(self): - """ - :returns: The commands_usage - :rtype: dict - """ - return self._properties['commands_usage'] - @property - def commands_costs(self): - """ - :returns: The commands_costs - :rtype: dict - """ - return self._properties['commands_costs'] +class UsageList(ListResource): - @property - def data_usage(self): - """ - :returns: The data_usage - :rtype: dict + def __init__(self, version: Version, sim_sid: str): """ - return self._properties['data_usage'] + Initialize the UsageList - @property - def data_costs(self): - """ - :returns: The data_costs - :rtype: dict - """ - return self._properties['data_costs'] + :param version: Version that contains the resource + :param sim_sid: - @property - def url(self): """ - :returns: The url - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + + def get(self) -> UsageContext: """ - return self._properties['url'] + Constructs a UsageContext - def fetch(self, end=values.unset, start=values.unset): """ - Fetch the UsageInstance + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) - :param unicode end: The end - :param unicode start: The start + def __call__(self) -> UsageContext: + """ + Constructs a UsageContext - :returns: The 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 9965daed53..91da8751d9 100644 --- a/twilio/rest/pricing/__init__.py +++ b/twilio/rest/pricing/__init__.py @@ -1,79 +1,55 @@ -# coding=utf-8 -r""" -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.v2 import V2 +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 - self._v2 = 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 v2(self): - """ - :returns: Version v2 of pricing - :rtype: twilio.rest.pricing.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 - - @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.v2.voice.VoiceList - """ + 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 68d31d007f..ba8b65885d 100644 --- a/twilio/rest/pricing/v1/__init__.py +++ b/twilio/rest/pricing/v1/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 f6036dc7e3..df5c148b81 100644 --- a/twilio/rest/pricing/v1/messaging/__init__.py +++ b/twilio/rest/pricing/v1/messaging/__init__.py @@ -1,150 +1,54 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.get('name'), - 'url': payload.get('url'), - 'links': payload.get('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 7a820c0dc0..49360cd85c 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -1,327 +1,415 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 code + 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 code - :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): - """ - 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 CountryPage(Page): - """ """ + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.pricing.v1.messaging.country.CountryPage - :rtype: twilio.rest.pricing.v1.messaging.country.CountryPage + :returns: Machine friendly representation """ - super(CountryPage, 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 CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + :param payload: Payload response from the API """ - return CountryInstance(self._version, payload, ) + return CountryInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CountryContext(InstanceContext): - """ """ +class CountryList(ListResource): - def __init__(self, version, iso_country): + def __init__(self, version: Version): """ - Initialize the CountryContext + Initialize the CountryList - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.messaging.country.CountryContext - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext """ - super(CountryContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Messaging/Countries/{iso_country}'.format(**self._solution) + self._uri = "/Messaging/Countries" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Fetch the 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. - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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[CountryInstance]: """ - Provide a friendly representation + 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. - :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 CountryInstance(InstanceResource): - """ """ + 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. - def __init__(self, version, payload, iso_country=None): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Initialize the CountryInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.pricing.v1.messaging.country.CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - super(CountryInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'outbound_sms_prices': payload.get('outbound_sms_prices'), - 'inbound_sms_prices': payload.get('inbound_sms_prices'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + :param page_token: PageToken provided by the 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 _proxy(self): + :returns: Page of CountryInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.messaging.country.CountryContext - """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] + headers["Accept"] = "application/json" - @property - def iso_country(self): - """ - :returns: The ISO country code - :rtype: unicode - """ - return self._properties['iso_country'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - @property - def outbound_sms_prices(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, + ) -> CountryPage: """ - :returns: The list of OutboundSMSPrice records - :rtype: unicode + 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 """ - return self._properties['outbound_sms_prices'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def inbound_sms_prices(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 CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The list of InboundPrice records - :rtype: unicode + 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 """ - return self._properties['inbound_sms_prices'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def price_unit(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + 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 """ - 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 absolute URL of the resource - :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 the CountryInstance + Constructs a CountryContext - :returns: The 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 787e4d64b2..429ce9b14c 100644 --- a/twilio/rest/pricing/v1/phone_number/__init__.py +++ b/twilio/rest/pricing/v1/phone_number/__init__.py @@ -1,150 +1,54 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.get('name'), - 'url': payload.get('url'), - 'links': payload.get('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 007373d9ef..2d11cd1c3e 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -1,318 +1,413 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 code + 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 code - :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): - """ - 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 CountryPage(Page): - """ """ + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.pricing.v1.phone_number.country.CountryPage - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryPage + :returns: Machine friendly representation """ - super(CountryPage, 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 CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance - :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 + :param payload: Payload response from the API """ - return CountryInstance(self._version, payload, ) + return CountryInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CountryContext(InstanceContext): - """ """ +class CountryList(ListResource): - def __init__(self, version, iso_country): + def __init__(self, version: Version): """ - Initialize the CountryContext + Initialize the CountryList - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.phone_number.country.CountryContext - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext """ - super(CountryContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/PhoneNumbers/Countries/{iso_country}'.format(**self._solution) + self._uri = "/PhoneNumbers/Countries" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Fetch the 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. - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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[CountryInstance]: """ - Provide a friendly representation + 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. - :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 CountryInstance(InstanceResource): - """ """ + 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. - def __init__(self, version, payload, iso_country=None): + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - Initialize the CountryInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.pricing.v1.phone_number.country.CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - super(CountryInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'phone_number_prices': payload.get('phone_number_prices'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + :param page_token: PageToken provided by the 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 _proxy(self): + :returns: Page of CountryInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.phone_number.country.CountryContext - """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] + headers["Accept"] = "application/json" - @property - def iso_country(self): + 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: """ - :returns: The ISO country code - :rtype: unicode + 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 """ - return self._properties['iso_country'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def phone_number_prices(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 CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The list of PhoneNumberPrices records - :rtype: unicode + 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 """ - return self._properties['phone_number_prices'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def price_unit(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + 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 """ - 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 absolute URL of the resource - :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 the CountryInstance + Constructs a CountryContext - :returns: The 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 68a6222903..a801a30089 100644 --- a/twilio/rest/pricing/v1/voice/__init__.py +++ b/twilio/rest/pricing/v1/voice/__init__.py @@ -1,164 +1,65 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.get('name'), - 'url': payload.get('url'), - 'links': payload.get('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 1ba58c7840..7fb0da883a 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -1,327 +1,417 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 code + 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 code - :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): - """ - 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 CountryPage(Page): - """ """ + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.pricing.v1.voice.country.CountryPage - :rtype: twilio.rest.pricing.v1.voice.country.CountryPage + :returns: Machine friendly representation """ - super(CountryPage, 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 CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + :param payload: Payload response from the API """ - return CountryInstance(self._version, payload, ) + return CountryInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CountryContext(InstanceContext): - """ """ +class CountryList(ListResource): - def __init__(self, version, iso_country): + def __init__(self, version: Version): """ - Initialize the CountryContext + Initialize the CountryList - :param Version version: Version that contains the resource - :param iso_country: The ISO country code + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v1.voice.country.CountryContext - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext """ - super(CountryContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Voice/Countries/{iso_country}'.format(**self._solution) + self._uri = "/Voice/Countries" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Fetch the 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. - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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[CountryInstance]: """ - Provide a friendly representation + 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. - :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 CountryInstance(InstanceResource): - """ """ + 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) - def __init__(self, version, payload, iso_country=None): + :returns: list that will contain up to limit results """ - Initialize the CountryInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.pricing.v1.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - super(CountryInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'outbound_prefix_prices': payload.get('outbound_prefix_prices'), - 'inbound_call_prices': payload.get('inbound_call_prices'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + :param page_token: PageToken provided by the 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 _proxy(self): + :returns: Page of CountryInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v1.voice.country.CountryContext - """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] + headers["Accept"] = "application/json" - @property - def iso_country(self): - """ - :returns: The ISO country code - :rtype: unicode - """ - return self._properties['iso_country'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - @property - def outbound_prefix_prices(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, + ) -> CountryPage: """ - :returns: The list of OutboundPrefixPrice records - :rtype: unicode + 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 """ - return self._properties['outbound_prefix_prices'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def inbound_call_prices(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 CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The list of InboundCallPrice records - :rtype: unicode + 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 """ - return self._properties['inbound_call_prices'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def price_unit(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + 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 """ - 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 absolute URL of the resource - :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 the CountryInstance + Constructs a CountryContext - :returns: The 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 cb8b14da5c..5bff8cd5d6 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -1,258 +1,197 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 phone number to fetch - :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 phone number to fetch - :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 phone number to fetch - :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 the NumberInstance + headers["Accept"] = "application/json" - :returns: The fetched NumberInstance - :rtype: twilio.rest.pricing.v1.voice.number.NumberInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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.get('number'), - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'outbound_call_price': payload.get('outbound_call_price'), - 'inbound_call_price': payload.get('inbound_call_price'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('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 phone number - :rtype: unicode - """ - return self._properties['number'] - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] +class NumberList(ListResource): - @property - def iso_country(self): - """ - :returns: The ISO country code - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['iso_country'] + Initialize the NumberList - @property - def outbound_call_price(self): - """ - :returns: The OutboundCallPrice record - :rtype: unicode - """ - return self._properties['outbound_call_price'] + :param version: Version that contains the resource - @property - def inbound_call_price(self): """ - :returns: The InboundCallPrice record - :rtype: unicode - """ - return self._properties['inbound_call_price'] + super().__init__(version) - @property - def price_unit(self): - """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + def get(self, number: str) -> NumberContext: """ - return self._properties['price_unit'] + Constructs a NumberContext - @property - def url(self): + :param number: The phone number to fetch. """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + return NumberContext(self._version, number=number) - def fetch(self): + def __call__(self, number: str) -> NumberContext: """ - Fetch the NumberInstance + Constructs a NumberContext - :returns: The 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 index 08377624a0..d0fd67f737 100644 --- a/twilio/rest/pricing/v2/__init__.py +++ b/twilio/rest/pricing/v2/__init__.py @@ -1,42 +1,59 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Pricing - :returns: V2 version of Pricing - :rtype: twilio.rest.pricing.v2.V2.V2 + :param domain: The Twilio.pricing domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._voice = None + super().__init__(domain, "v2") + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + self._voice: Optional[VoiceList] = None @property - def voice(self): - """ - :rtype: twilio.rest.pricing.v2.voice.VoiceList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + 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 index 3b9b865aef..1ebbcbb644 100644 --- a/twilio/rest/pricing/v2/voice/__init__.py +++ b/twilio/rest/pricing/v2/voice/__init__.py @@ -1,164 +1,65 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.v2.voice.country import CountryList from twilio.rest.pricing.v2.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.v2.voice.VoiceList - :rtype: twilio.rest.pricing.v2.voice.VoiceList """ - super(VoiceList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/Voice" - # Components - self._countries = None - self._numbers = None + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None @property - def countries(self): + def countries(self) -> CountryList: """ Access the countries - - :returns: twilio.rest.pricing.v2.voice.country.CountryList - :rtype: twilio.rest.pricing.v2.voice.country.CountryList """ if self._countries is None: - self._countries = CountryList(self._version, ) + self._countries = CountryList(self._version) return self._countries @property - def numbers(self): + def numbers(self) -> NumberList: """ Access the numbers - - :returns: twilio.rest.pricing.v2.voice.number.NumberList - :rtype: twilio.rest.pricing.v2.voice.number.NumberList """ if self._numbers is None: - self._numbers = NumberList(self._version, ) + self._numbers = NumberList(self._version) return self._numbers - 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.v2.voice.VoicePage - :rtype: twilio.rest.pricing.v2.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.v2.voice.VoiceInstance - :rtype: twilio.rest.pricing.v2.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.v2.voice.VoiceInstance - :rtype: twilio.rest.pricing.v2.voice.VoiceInstance - """ - super(VoiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'name': payload.get('name'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {} - - @property - def name(self): - """ - :returns: The resource name - :rtype: unicode - """ - return self._properties['name'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The URLs of the related Countries and Numbers resources - :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/v2/voice/country.py b/twilio/rest/pricing/v2/voice/country.py index 4111cb6f03..997f368462 100644 --- a/twilio/rest/pricing/v2/voice/country.py +++ b/twilio/rest/pricing/v2/voice/country.py @@ -1,327 +1,417 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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](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") - :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.v2.voice.country.CountryList - :rtype: twilio.rest.pricing.v2.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.v2.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']) - 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.v2.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.v2.voice.country.CountryPage +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CountryContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - 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.v2.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 code of the pricing information to fetch + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.pricing.v2.voice.country.CountryContext - :rtype: twilio.rest.pricing.v2.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 code of the pricing information to fetch - :returns: twilio.rest.pricing.v2.voice.country.CountryContext - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext + :returns: The fetched CountryInstance """ - return CountryContext(self._version, iso_country=iso_country, ) - 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 CountryPage(Page): - """ """ + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the CountryPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Provide a friendly representation - :returns: twilio.rest.pricing.v2.voice.country.CountryPage - :rtype: twilio.rest.pricing.v2.voice.country.CountryPage + :returns: Machine friendly representation """ - super(CountryPage, 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 CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.pricing.v2.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + :param payload: Payload response from the API """ - return CountryInstance(self._version, payload, ) + return CountryInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CountryContext(InstanceContext): - """ """ +class CountryList(ListResource): - def __init__(self, version, iso_country): + def __init__(self, version: Version): """ - Initialize the CountryContext + Initialize the CountryList - :param Version version: Version that contains the resource - :param iso_country: The ISO country code of the pricing information to fetch + :param version: Version that contains the resource - :returns: twilio.rest.pricing.v2.voice.country.CountryContext - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext """ - super(CountryContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'iso_country': iso_country, } - self._uri = '/Voice/Countries/{iso_country}'.format(**self._solution) + self._uri = "/Voice/Countries" - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: """ - Fetch the 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. - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return CountryInstance(self._version, payload, iso_country=self._solution['iso_country'], ) + 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[CountryInstance]: """ - Provide a friendly representation + 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. - :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 CountryInstance(InstanceResource): - """ """ + 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) - def __init__(self, version, payload, iso_country=None): + :returns: list that will contain up to limit results """ - Initialize the CountryInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.pricing.v2.voice.country.CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: """ - super(CountryInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'outbound_prefix_prices': payload.get('outbound_prefix_prices'), - 'inbound_call_prices': payload.get('inbound_call_prices'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('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) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 - # Context - self._context = None - self._solution = {'iso_country': iso_country or self._properties['iso_country'], } + :param page_token: PageToken provided by the 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 _proxy(self): + :returns: Page of CountryInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: CountryContext for this CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryContext - """ - if self._context is None: - self._context = CountryContext(self._version, iso_country=self._solution['iso_country'], ) - return self._context + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] + headers["Accept"] = "application/json" - @property - def iso_country(self): - """ - :returns: The ISO country code - :rtype: unicode - """ - return self._properties['iso_country'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - @property - def outbound_prefix_prices(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, + ) -> CountryPage: """ - :returns: The list of OutboundPrefixPriceWithOrigin records - :rtype: unicode + 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 """ - return self._properties['outbound_prefix_prices'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def inbound_call_prices(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 CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The list of InboundCallPrice records - :rtype: unicode + 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 """ - return self._properties['inbound_call_prices'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def price_unit(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + 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 """ - 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 absolute URL of the resource - :rtype: unicode + 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 self._properties['url'] + return CountryContext(self._version, iso_country=iso_country) - def fetch(self): + def __call__(self, iso_country: str) -> CountryContext: """ - Fetch the CountryInstance + Constructs a CountryContext - :returns: The fetched CountryInstance - :rtype: twilio.rest.pricing.v2.voice.country.CountryInstance + :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 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/v2/voice/number.py b/twilio/rest/pricing/v2/voice/number.py index a0dff09e0b..97a3a526ff 100644 --- a/twilio/rest/pricing/v2/voice/number.py +++ b/twilio/rest/pricing/v2/voice/number.py @@ -1,282 +1,234 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page - - -class NumberList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the NumberList - - :param Version version: Version that contains the resource +from twilio.base.version import Version - :returns: twilio.rest.pricing.v2.voice.number.NumberList - :rtype: twilio.rest.pricing.v2.voice.number.NumberList - """ - super(NumberList, self).__init__(version) - # Path Solution - self._solution = {} - - def get(self, destination_number): - """ - Constructs a NumberContext - - :param destination_number: The destination number for which to fetch pricing information - - :returns: twilio.rest.pricing.v2.voice.number.NumberContext - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext - """ - return NumberContext(self._version, destination_number=destination_number, ) - - def __call__(self, destination_number): - """ - Constructs a NumberContext - - :param destination_number: The destination number for which to fetch pricing information +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") - :returns: twilio.rest.pricing.v2.voice.number.NumberContext - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext - """ - return NumberContext(self._version, destination_number=destination_number, ) + self._solution = { + "destination_number": destination_number or self.destination_number, + } + self._context: Optional[NumberContext] = None - def __repr__(self): + @property + def _proxy(self) -> "NumberContext": """ - Provide a 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 - :returns: Machine friendly representation - :rtype: str + :returns: NumberContext for this NumberInstance """ - return '' - - -class NumberPage(Page): - """ """ + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context - def __init__(self, version, response, solution): + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": """ - Initialize the NumberPage + Fetch the NumberInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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: twilio.rest.pricing.v2.voice.number.NumberPage - :rtype: twilio.rest.pricing.v2.voice.number.NumberPage + :returns: The fetched NumberInstance """ - super(NumberPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch( + origination_number=origination_number, + ) - def get_instance(self, payload): + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": """ - Build an instance of NumberInstance + Asynchronous coroutine to fetch the NumberInstance - :param dict payload: Payload response from the API + :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: twilio.rest.pricing.v2.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance + :returns: The fetched NumberInstance """ - return NumberInstance(self._version, payload, ) + return await self._proxy.fetch_async( + origination_number=origination_number, + ) - 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 NumberContext(InstanceContext): - """ """ - def __init__(self, version, destination_number): + def __init__(self, version: Version, destination_number: str): """ Initialize the NumberContext - :param Version version: Version that contains the resource - :param destination_number: The destination number for which to fetch pricing information - - :returns: twilio.rest.pricing.v2.voice.number.NumberContext - :rtype: twilio.rest.pricing.v2.voice.number.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(NumberContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'destination_number': destination_number, } - self._uri = '/Voice/Numbers/{destination_number}'.format(**self._solution) + self._solution = { + "destination_number": destination_number, + } + self._uri = "/Voice/Numbers/{destination_number}".format(**self._solution) - def fetch(self, origination_number=values.unset): + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: """ Fetch the NumberInstance - :param unicode origination_number: The origination number for which to fetch pricing information + :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 - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance """ - data = values.of({'OriginationNumber': origination_number, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + 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'], + destination_number=self._solution["destination_number"], ) - def __repr__(self): + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the NumberInstance - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :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 + """ -class NumberInstance(InstanceResource): - """ """ + data = values.of( + { + "OriginationNumber": origination_number, + } + ) - def __init__(self, version, payload, destination_number=None): - """ - Initialize the NumberInstance + headers = values.of({}) - :returns: twilio.rest.pricing.v2.voice.number.NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance - """ - super(NumberInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'destination_number': payload.get('destination_number'), - 'origination_number': payload.get('origination_number'), - 'country': payload.get('country'), - 'iso_country': payload.get('iso_country'), - 'outbound_call_prices': payload.get('outbound_call_prices'), - 'inbound_call_price': payload.get('inbound_call_price'), - 'price_unit': payload.get('price_unit'), - 'url': payload.get('url'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = { - 'destination_number': destination_number or self._properties['destination_number'], - } + 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 NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) - :returns: NumberContext for this NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberContext + def __repr__(self) -> str: """ - if self._context is None: - self._context = NumberContext( - self._version, - destination_number=self._solution['destination_number'], - ) - return self._context + Provide a friendly representation - @property - def destination_number(self): - """ - :returns: The destination phone number, in E.164 format - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['destination_number'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def origination_number(self): - """ - :returns: The origination phone number, in E.164 format - :rtype: unicode - """ - return self._properties['origination_number'] - @property - def country(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['country'] +class NumberList(ListResource): - @property - def iso_country(self): + def __init__(self, version: Version): """ - :returns: The ISO country code - :rtype: unicode - """ - return self._properties['iso_country'] + Initialize the NumberList - @property - def outbound_call_prices(self): - """ - :returns: The list of OutboundCallPriceWithOrigin records - :rtype: unicode - """ - return self._properties['outbound_call_prices'] + :param version: Version that contains the resource - @property - def inbound_call_price(self): - """ - :returns: The InboundCallPrice record - :rtype: unicode """ - return self._properties['inbound_call_price'] + super().__init__(version) - @property - def price_unit(self): - """ - :returns: The currency in which prices are measured, in ISO 4127 format (e.g. usd, eur, jpy) - :rtype: unicode + def get(self, destination_number: str) -> NumberContext: """ - return self._properties['price_unit'] + Constructs a NumberContext - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode + :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 self._properties['url'] + return NumberContext(self._version, destination_number=destination_number) - def fetch(self, origination_number=values.unset): + def __call__(self, destination_number: str) -> NumberContext: """ - Fetch the NumberInstance - - :param unicode origination_number: The origination number for which to fetch pricing information + Constructs a NumberContext - :returns: The fetched NumberInstance - :rtype: twilio.rest.pricing.v2.voice.number.NumberInstance + :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 self._proxy.fetch(origination_number=origination_number, ) + return NumberContext(self._version, destination_number=destination_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/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 8086868b43..aec2a3d1af 100644 --- a/twilio/rest/proxy/__init__.py +++ b/twilio/rest/proxy/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -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 ee5122ab0d..83737dc0fb 100644 --- a/twilio/rest/proxy/v1/__init__.py +++ b/twilio/rest/proxy/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 d47d4950a3..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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() + + 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 str target_url: API-generated URL for the requested results page + :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: Page of ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ServicePage(self._version, response, self._solution) + 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. - 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, - chat_instance_sid=values.unset): + :returns: The updated ServiceInstance """ - Create the ServiceInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode default_ttl: Default TTL for a Session, in seconds - :param unicode callback_url: The URL we should call when the interaction status changes - :param ServiceInstance.GeoMatchLevel geo_match_level: Where a proxy number must be located relative to the participant identifier - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: The preference for Proxy Number selection for the Service instance - :param unicode intercept_callback_url: The URL we call on each interaction - :param unicode out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session - :param unicode chat_instance_sid: The SID of the Chat Service Instance + 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, + ) - :returns: The created ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance + @property + def phone_numbers(self) -> PhoneNumberList: """ - 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, ) - - def get(self, sid): + Access the phone_numbers """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + return self._proxy.phone_numbers - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + @property + def sessions(self) -> SessionList: """ - return ServiceContext(self._version, sid=sid, ) - - def __call__(self, sid): + Access the sessions """ - Constructs a ServiceContext - - :param sid: The unique string that identifies the resource + return self._proxy.sessions - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes """ - return ServiceContext(self._version, sid=sid, ) + 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 - - 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._phone_numbers: Optional[PhoneNumberList] = None + self._sessions: Optional[SessionList] = None + self._short_codes: Optional[ShortCodeList] = None - :returns: twilio.rest.proxy.v1.service.ServiceInstance - :rtype: twilio.rest.proxy.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 unique string that identifies the resource - :returns: twilio.rest.proxy.v1.service.ServiceContext - :rtype: twilio.rest.proxy.v1.service.ServiceContext + :returns: True if delete succeeds, False otherwise """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._sessions = None - self._phone_numbers = None - self._short_codes = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ServiceInstance: """ Fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.proxy.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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"], + ) - def delete(self): + async def fetch_async(self) -> ServiceInstance: """ - Deletes the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ServiceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - 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, - chat_instance_sid=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode default_ttl: Default TTL for a Session, in seconds - :param unicode callback_url: The URL we should call when the interaction status changes - :param ServiceInstance.GeoMatchLevel geo_match_level: Where a proxy number must be located relative to the participant identifier - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: The preference for Proxy Number selection for the Service instance - :param unicode intercept_callback_url: The URL we call on each interaction - :param unicode out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session - :param unicode chat_instance_sid: The SID of the Chat Service Instance + :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 - :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, - 'ChatInstanceSid': chat_instance_sid, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def sessions(self): - """ - Access the sessions + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList + 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 """ - if self._sessions is None: - self._sessions = SessionList(self._version, service_sid=self._solution['sid'], ) - return self._sessions + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def phone_numbers(self): + 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" - - class NumberSelectionBehavior(object): - AVOID_STICKY = "avoid-sticky" - PREFER_STICKY = "prefer-sticky" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'chat_instance_sid': payload.get('chat_instance_sid'), - 'callback_url': payload.get('callback_url'), - 'default_ttl': deserialize.integer(payload.get('default_ttl')), - 'number_selection_behavior': payload.get('number_selection_behavior'), - 'geo_match_level': payload.get('geo_match_level'), - 'intercept_callback_url': payload.get('intercept_callback_url'), - 'out_of_session_callback_url': payload.get('out_of_session_callback_url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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: The unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def chat_instance_sid(self): - """ - :returns: The SID of the Chat Service Instance - :rtype: unicode - """ - return self._properties['chat_instance_sid'] +class ServiceList(ListResource): - @property - def callback_url(self): + def __init__(self, version: Version): """ - :returns: The URL we call when the interaction status changes - :rtype: unicode - """ - return self._properties['callback_url'] + Initialize the ServiceList - @property - def default_ttl(self): - """ - :returns: Default TTL for a Session, in seconds - :rtype: unicode - """ - return self._properties['default_ttl'] + :param version: Version that contains the resource - @property - def number_selection_behavior(self): - """ - :returns: The preference for Proxy Number selection for the Service instance - :rtype: ServiceInstance.NumberSelectionBehavior """ - return self._properties['number_selection_behavior'] + super().__init__(version) - @property - def geo_match_level(self): - """ - :returns: Where a proxy number must be located relative to the participant identifier - :rtype: ServiceInstance.GeoMatchLevel - """ - return self._properties['geo_match_level'] + self._uri = "/Services" - @property - def intercept_callback_url(self): - """ - :returns: The URL we call on each interaction - :rtype: unicode + 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: """ - return self._properties['intercept_callback_url'] + Create the ServiceInstance - @property - def out_of_session_callback_url(self): - """ - :returns: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session - :rtype: unicode + :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 """ - return self._properties['out_of_session_callback_url'] - @property - def date_created(self): + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + + 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Service 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: The URLs of resources related to the Service - :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 the ServiceInstance + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: The 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, + } + ) + + 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 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, + } + ) - 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, - chat_instance_sid=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 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: An application-defined string that uniquely identifies the resource - :param unicode default_ttl: Default TTL for a Session, in seconds - :param unicode callback_url: The URL we should call when the interaction status changes - :param ServiceInstance.GeoMatchLevel geo_match_level: Where a proxy number must be located relative to the participant identifier - :param ServiceInstance.NumberSelectionBehavior number_selection_behavior: The preference for Proxy Number selection for the Service instance - :param unicode intercept_callback_url: The URL we call on each interaction - :param unicode out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session - :param unicode chat_instance_sid: The SID of the Chat Service Instance + :param target_url: API-generated URL for the requested results page - :returns: The 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, - chat_instance_sid=chat_instance_sid, - ) + 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 - :returns: twilio.rest.proxy.v1.service.session.SessionList - :rtype: twilio.rest.proxy.v1.service.session.SessionList + :param target_url: API-generated URL for the requested results page + + :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 71747f10ab..3c8517cedd 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -1,465 +1,662 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the PhoneNumber resource's parent Service 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.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, - is_reserved=values.unset): + def delete(self) -> bool: """ - Create the PhoneNumberInstance + Deletes the PhoneNumberInstance - :param unicode sid: The SID of a Twilio IncomingPhoneNumber resource - :param unicode phone_number: The phone number in E.164 format - :param bool is_reserved: Whether the new phone number should be reserved - :returns: The 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, 'IsReserved': is_reserved, }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return PhoneNumberPage(self._version, response, self._solution) + return self._proxy.update( + is_reserved=is_reserved, + ) - 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: The unique string that identifies the resource +class PhoneNumberContext(InstanceContext): - :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + 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: The unique string that identifies the resource + # 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: The SID of the PhoneNumber resource's parent Service resource - :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: The SID of the parent Service resource of the PhoneNumber resource to fetch - :param sid: The unique string that identifies the resource - :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({}) - def delete(self): - """ - Deletes the PhoneNumberInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def fetch(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: """ - Fetch the PhoneNumberInstance + Update the PhoneNumberInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def update(self, is_reserved=values.unset): + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: """ - Update the PhoneNumberInstance + Asynchronous coroutine to update the PhoneNumberInstance - :param bool is_reserved: Whether the new phone number should be reserved + :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 - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance """ - data = values.of({'IsReserved': is_reserved, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'phone_number': payload.get('phone_number'), - 'friendly_name': payload.get('friendly_name'), - 'iso_country': payload.get('iso_country'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('url'), - 'is_reserved': payload.get('is_reserved'), - 'in_use': deserialize.integer(payload.get('in_use')), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class PhoneNumberPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ - 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 PhoneNumberInstance - :returns: PhoneNumberContext for this PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = PhoneNumberContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the PhoneNumber resource's parent Service resource - :rtype: unicode + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['service_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 date_created(self): """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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['date_created'] + Create the PhoneNumberInstance - @property - def date_updated(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 ISO 8601 date and time in GMT when the resource was last updated - :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 = 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['date_updated'] + Asynchronously create the PhoneNumberInstance - @property - def phone_number(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 phone number in E.164 format - :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 = 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['phone_number'] + 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 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 string that you assigned to describe the resource - :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[PhoneNumberInstance]: """ - return self._properties['friendly_name'] + 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 iso_country(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 ISO Country Code - :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['iso_country'] + 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 capabilities(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 capabilities of the phone number - :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['capabilities'] + 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 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 absolute URL of the PhoneNumber resource - :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['url'] + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def is_reserved(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: Reserve the phone number for manual assignment to participants only - :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 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['is_reserved'] + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately - @property - def in_use(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 number of open session assigned to the number. - :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['in_use'] + Retrieve a specific page of PhoneNumberInstance 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 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 - def fetch(self): + :returns: Page of PhoneNumberInstance """ - Fetch the PhoneNumberInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) - :returns: The fetched PhoneNumberInstance - :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberInstance + def get(self, sid: str) -> PhoneNumberContext: """ - return self._proxy.fetch() + Constructs a PhoneNumberContext - def update(self, is_reserved=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. """ - Update the PhoneNumberInstance + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param bool is_reserved: Whether the new phone number should be reserved + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext - :returns: The updated 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.update(is_reserved=is_reserved, ) + 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 d357162bfc..839db075c3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -1,593 +1,784 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the resource's parent Service + 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, 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. - - :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.proxy.v1.service.session.SessionInstance] + :returns: SessionContext for this SessionInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + if self._context is None: + self._context = SessionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(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. + Deletes the SessionInstance - :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(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 SessionInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the SessionInstance - :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: True if delete succeeds, False otherwise """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "SessionInstance": + """ + Fetch the SessionInstance - return SessionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched SessionInstance """ - 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 + return self._proxy.fetch() - :returns: Page of SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionPage + async def fetch_async(self) -> "SessionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the SessionInstance - return SessionPage(self._version, response, self._solution) - def create(self, unique_name=values.unset, date_expiry=values.unset, - ttl=values.unset, mode=values.unset, status=values.unset, - participants=values.unset): + :returns: The fetched SessionInstance """ - Create the SessionInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param datetime date_expiry: The ISO 8601 date when the Session should expire - :param unicode ttl: When the session will expire - :param SessionInstance.Mode mode: The Mode of the Session - :param SessionInstance.Status status: Session status - :param dict participants: The Participant objects to include in the new session + return await self._proxy.fetch_async() - :returns: The created SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "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)), - }) + Update the SessionInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :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: - return SessionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + :returns: The updated SessionInstance + """ + return self._proxy.update( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) - 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: The unique string that identifies the resource + :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: The unique string that identifies the resource + 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: + """ + Access the participants """ - return SessionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + 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: The SID of the resource's parent Service + 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) + + self._interactions: Optional[InteractionList] = None + self._participants: Optional[ParticipantList] = None - def get_instance(self, payload): + 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: The SID of the Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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({}) + + headers["Accept"] = "application/json" - # Dependents - self._interactions = None - self._participants = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SessionInstance: """ - Fetch the SessionInstance + Asynchronous coroutine to fetch the SessionInstance + :returns: The fetched SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, date_expiry=values.unset, ttl=values.unset, - status=values.unset): + data = values.of( + { + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: """ - Update the SessionInstance + Asynchronous coroutine to update the SessionInstance - :param datetime date_expiry: The ISO 8601 date when the Session should expire - :param unicode ttl: When the session will expire - :param SessionInstance.Status status: The new status of the resource + :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 - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance """ - data = values.of({ - 'DateExpiry': serialize.iso8601_datetime(date_expiry), - 'Ttl': ttl, - 'Status': status, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + 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. """ - - class Status(object): - OPEN = "open" - IN_PROGRESS = "in-progress" - CLOSED = "closed" - FAILED = "failed" - UNKNOWN = "unknown" + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - 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.get('sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'date_started': deserialize.iso8601_datetime(payload.get('date_started')), - 'date_ended': deserialize.iso8601_datetime(payload.get('date_ended')), - 'date_last_interaction': deserialize.iso8601_datetime(payload.get('date_last_interaction')), - 'date_expiry': deserialize.iso8601_datetime(payload.get('date_expiry')), - 'unique_name': payload.get('unique_name'), - 'status': payload.get('status'), - 'closed_reason': payload.get('closed_reason'), - 'ttl': deserialize.integer(payload.get('ttl')), - 'mode': payload.get('mode'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def service_sid(self): - """ - :returns: The SID of the resource's parent Service - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['service_sid'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def date_started(self): - """ - :returns: The ISO 8601 date when the Session started - :rtype: datetime - """ - return self._properties['date_started'] +class SessionList(ListResource): - @property - def date_ended(self): + def __init__(self, version: Version, service_sid: str): """ - :returns: The ISO 8601 date when the Session ended - :rtype: datetime - """ - return self._properties['date_ended'] + Initialize the SessionList - @property - def date_last_interaction(self): - """ - :returns: The ISO 8601 date when the Session last had an 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 ISO 8601 date when the Session should expire - :rtype: datetime - """ - return self._properties['date_expiry'] + super().__init__(version) - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + # 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: """ - return self._properties['unique_name'] + Create the SessionInstance - @property - def status(self): - """ - :returns: The status of the Session - :rtype: SessionInstance.Status - """ - return self._properties['status'] + :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. - @property - def closed_reason(self): - """ - :returns: The reason the Session ended - :rtype: unicode + :returns: The created SessionInstance """ - return self._properties['closed_reason'] - @property - def ttl(self): - """ - :returns: When the session will expire - :rtype: unicode + data = values.of( + { + "UniqueName": unique_name, + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Mode": mode, + "Status": status, + "Participants": serialize.map( + participants, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Asynchronously create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance """ - return self._properties['ttl'] - @property - def mode(self): + 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 the 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 ISO 8601 date and time in GMT when the resource 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Session 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: The URLs of resources related to the Session - :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" - def fetch(self): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: """ - Fetch the SessionInstance + Asynchronously retrieve a single page of SessionInstance records from the API. + Request is executed immediately - :returns: The fetched SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :param page_token: PageToken provided by the API + :param page_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._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 SessionPage(self._version, response, self._solution) + + 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, date_expiry=values.unset, ttl=values.unset, - status=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 datetime date_expiry: The ISO 8601 date when the Session should expire - :param unicode ttl: When the session will expire - :param SessionInstance.Status status: The new status of the resource + :param target_url: API-generated URL for the requested results page - :returns: The updated SessionInstance - :rtype: twilio.rest.proxy.v1.service.session.SessionInstance + :returns: Page of SessionInstance """ - return self._proxy.update(date_expiry=date_expiry, ttl=ttl, status=status, ) + 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 ea5adf48e5..7eeccda5bc 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -1,531 +1,571 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session + 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, 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 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(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 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 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(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) -> "InteractionInstance": """ - Retrieve a single page of InteractionInstance records from the API. - Request is executed immediately + Fetch the InteractionInstance - :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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: The unique string that identifies the resource + 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: The unique string that identifies the resource - :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: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session - :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: The SID of the parent Service of the resource to fetch - :param session_sid: he SID of the parent Session of the resource to fetch - :param sid: The unique string that identifies the resource + 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 the InteractionInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: The fetched InteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance + +class InteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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(method='DELETE', uri=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.get('sid'), - 'session_sid': payload.get('session_sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'data': payload.get('data'), - 'type': payload.get('type'), - 'inbound_participant_sid': payload.get('inbound_participant_sid'), - 'inbound_resource_sid': payload.get('inbound_resource_sid'), - 'inbound_resource_status': payload.get('inbound_resource_status'), - 'inbound_resource_type': payload.get('inbound_resource_type'), - 'inbound_resource_url': payload.get('inbound_resource_url'), - 'outbound_participant_sid': payload.get('outbound_participant_sid'), - 'outbound_resource_sid': payload.get('outbound_resource_sid'), - 'outbound_resource_status': payload.get('outbound_resource_status'), - 'outbound_resource_type': payload.get('outbound_resource_type'), - 'outbound_resource_url': payload.get('outbound_resource_url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: The unique string that identifies the resource - :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: The SID of the resource's parent Session - :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[InteractionInstance]: """ - :returns: The SID of the resource's parent Service - :rtype: unicode - """ - 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: The SID of the Account that created the resource - :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: A JSON string that includes the message body of message interactions - :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 the Interaction - :rtype: InteractionInstance.Type - """ - return self._properties['type'] + return self._version.stream_async(page, limits["limit"]) - @property - def inbound_participant_sid(self): - """ - :returns: The SID of the inbound Participant resource - :rtype: unicode + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: """ - 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: The SID of the inbound resource - :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: list that will contain up to limit results """ - :returns: The inbound resource status of the Interaction - :rtype: InteractionInstance.ResourceStatus - """ - return self._properties['inbound_resource_status'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def inbound_resource_type(self): - """ - :returns: The inbound resource type - :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 inbound 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: The SID of the outbound Participant - :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: The SID of the outbound resource - :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 the 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 outbound resource type - :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 outbound 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 ISO 8601 date and time in GMT when the 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Interaction 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 the InteractionInstance + Constructs a InteractionContext - :returns: The 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 f6b611e69d..7ad20fcffb 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -1,509 +1,634 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - def __init__(self, version, service_sid, session_sid): + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": """ - 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: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session + :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, 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 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(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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 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(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) -> "ParticipantInstance": """ - Retrieve a single page of ParticipantInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ParticipantInstance - :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + @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 the ParticipantInstance + Deletes the ParticipantInstance - :param unicode identifier: The phone number of the Participant - :param unicode friendly_name: The string that you assigned to describe the participant - :param unicode proxy_identifier: The proxy phone number to use for the Participant - :param unicode proxy_identifier_sid: The Proxy Identifier Sid - :returns: The 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(method='POST', uri=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: The unique string that identifies the resource - :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: The unique string that identifies the resource - :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 + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, response, solution): + @property + def message_interactions(self) -> MessageInteractionList: """ - Initialize the ParticipantPage + Access the message_interactions + """ + if self._message_interactions is None: + self._message_interactions = MessageInteractionList( + self._version, + self._solution["service_sid"], + self._solution["session_sid"], + self._solution["sid"], + ) + return self._message_interactions - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session + 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: The SID of the parent Service of the resource to fetch - :param session_sid: The SID of the parent Session of the resource to fetch - :param sid: The unique string that identifies the resource + :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 the ParticipantInstance + Create the ParticipantInstance - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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. - @property - def message_interactions(self): + :returns: The created ParticipantInstance """ - Access the message_interactions - :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList + data = values.of( + { + "Identifier": identifier, + "FriendlyName": friendly_name, + "ProxyIdentifier": proxy_identifier, + "ProxyIdentifierSid": proxy_identifier_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: """ - 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 + 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): + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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[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.get('sid'), - 'session_sid': payload.get('session_sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'identifier': payload.get('identifier'), - 'proxy_identifier': payload.get('proxy_identifier'), - 'proxy_identifier_sid': payload.get('proxy_identifier_sid'), - 'date_deleted': deserialize.iso8601_datetime(payload.get('date_deleted')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: """ - 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: The SID of the resource's parent Session - :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: list that will contain up to limit results """ - :returns: The SID of the resource's parent Service - :rtype: unicode - """ - 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): - """ - :returns: The SID of the Account that created the resource - :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, + ) -> ParticipantPage: """ - 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: The string that you assigned to describe the participant - :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 the 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 phone number or short code of the participant's partner - :rtype: unicode - """ - return self._properties['proxy_identifier'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def proxy_identifier_sid(self): - """ - :returns: The SID of the Proxy Identifier assigned to the Participant - :rtype: unicode - """ - return self._properties['proxy_identifier_sid'] + headers["Accept"] = "application/json" - @property - def date_deleted(self): - """ - :returns: The ISO 8601 date the Participant was removed - :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): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :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, + ) -> ParticipantPage: """ - 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the Participant 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): + headers = values.of({"Content-Type": "application/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: """ - :returns: The URLs to resources related the participant - :rtype: unicode + 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 """ - return self._properties['links'] + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> ParticipantPage: """ - Fetch the ParticipantInstance + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.ParticipantInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> ParticipantContext: """ - Deletes the ParticipantInstance + Constructs a ParticipantContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. """ - return self._proxy.delete() + 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 c033debfc3..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,564 +1,622 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session - :param participant_sid: The SID of the Participant resource + 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 the MessageInteractionInstance - - :param unicode body: Message body - :param unicode media_url: Reserved + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance + :returns: MessageInteractionContext for this MessageInteractionInstance """ - data = values.of({'Body': body, 'MediaUrl': serialize.map(media_url, lambda e: e), }) - - payload = self._version.create(method='POST', uri=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'], - ) + if self._context is None: + self._context = MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(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. + 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 self._proxy.fetch() - page = self.page(page_size=limits['page_size'], ) + async def fetch_async(self) -> "MessageInteractionInstance": + """ + Asynchronous coroutine to fetch the MessageInteractionInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched MessageInteractionInstance """ - Lists MessageInteractionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param 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.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance] + 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 MessageInteractionInstance 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 MessageInteractionInstance - :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionPage +class MessageInteractionContext(InstanceContext): + + def __init__( + self, + version: Version, + service_sid: str, + session_sid: str, + participant_sid: str, + sid: str, + ): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the MessageInteractionContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + super().__init__(version) - return MessageInteractionPage(self._version, response, self._solution) + # 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 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: The unique string that identifies the resource + 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: The unique string that identifies the resource - :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: The SID of the resource's parent Service - :param session_sid: The SID of the resource's parent Session - :param participant_sid: The SID of the Participant resource - - :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: The SID of the Service to fetch the resource from - :param session_sid: The SID of the parent Session - :param participant_sid: The SID of the Participant resource - :param sid: The unique string that identifies the resource + :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 the MessageInteractionInstance + Create the MessageInteractionInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + :returns: The created MessageInteractionInstance + """ -class MessageInteractionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class Type(object): - MESSAGE = "message" - VOICE = "voice" - UNKNOWN = "unknown" + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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.get('sid'), - 'session_sid': payload.get('session_sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'data': payload.get('data'), - 'type': payload.get('type'), - 'participant_sid': payload.get('participant_sid'), - 'inbound_participant_sid': payload.get('inbound_participant_sid'), - 'inbound_resource_sid': payload.get('inbound_resource_sid'), - 'inbound_resource_status': payload.get('inbound_resource_status'), - 'inbound_resource_type': payload.get('inbound_resource_type'), - 'inbound_resource_url': payload.get('inbound_resource_url'), - 'outbound_participant_sid': payload.get('outbound_participant_sid'), - 'outbound_resource_sid': payload.get('outbound_resource_sid'), - 'outbound_resource_status': payload.get('outbound_resource_status'), - 'outbound_resource_type': payload.get('outbound_resource_type'), - 'outbound_resource_url': payload.get('outbound_resource_url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: The unique string that identifies the resource - :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: The SID of the resource's parent Session - :rtype: unicode - """ - return self._properties['session_sid'] + return self._version.stream(page, limits["limit"]) - @property - def service_sid(self): - """ - :returns: The SID of the resource's parent Service - :rtype: unicode + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInteractionInstance]: """ - 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: The SID of the Account that created the resource - :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: A JSON string that includes the message body sent to the participant - :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 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: The SID of the Participant resource - :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: Always empty for Message Interactions - :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: Always empty for Message Interactions - :rtype: unicode + :returns: list that will contain up to limit results """ - return self._properties['inbound_resource_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def inbound_resource_status(self): - """ - :returns: Always empty for Message Interactions - :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: Always empty for Message Interactions - :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: Always empty for Message Interactions - :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: The SID of the outbound Participant resource - :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: The SID of the outbound Message resource - :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 - :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 outbound resource type - :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 message 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 ISO 8601 date and time in GMT when the resource 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the MessageInteraction 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 the MessageInteractionInstance + Constructs a MessageInteractionContext - :returns: The 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 9afbc40d4f..df71d4bdd5 100644 --- a/twilio/rest/proxy/v1/service/short_code.py +++ b/twilio/rest/proxy/v1/service/short_code.py @@ -1,444 +1,638 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the resource's parent Service + 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 the ShortCodeInstance + Deletes the ShortCodeInstance - :param unicode sid: The SID of a Twilio ShortCode resource - :returns: The 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(method='POST', uri=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. + 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.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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ShortCodePage(self._version, response, self._solution) + return self._proxy.update( + is_reserved=is_reserved, + ) - 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: The unique string that identifies the resource - :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: The unique string that identifies the resource + # 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: The SID of the resource's parent Service - :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({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - 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.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: The SID of the parent Service to fetch the resource from - :param sid: The unique string that identifies the resource - :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): - """ - Deletes the ShortCodeInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + 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 fetch(self): + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: """ - Fetch the ShortCodeInstance + Update the ShortCodeInstance - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def update(self, is_reserved=values.unset): + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: """ - Update the ShortCodeInstance + Asynchronous coroutine to update the ShortCodeInstance - :param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only + :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 - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance """ - data = values.of({'IsReserved': is_reserved, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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. """ - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the ShortCodeInstance - - :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance - """ - super(ShortCodeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'short_code': payload.get('short_code'), - 'iso_country': payload.get('iso_country'), - 'capabilities': payload.get('capabilities'), - 'url': payload.get('url'), - 'is_reserved': payload.get('is_reserved'), - } +class ShortCodePage(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]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance - @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 ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - :returns: ShortCodeContext for this ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeContext + def __repr__(self) -> str: """ - if self._context is None: - self._context = ShortCodeContext( - 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: The unique string that identifies the resource - :rtype: unicode + return "" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - return self._properties['sid'] + 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. - @property - def account_sid(self): """ - :returns: The SID of the Account that created the resource - :rtype: unicode + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, sid: str) -> ShortCodeInstance: """ - return self._properties['account_sid'] + Create the ShortCodeInstance - @property - def service_sid(self): + :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 """ - :returns: The SID of the resource's parent Service - :rtype: unicode + + 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: """ - return self._properties['service_sid'] + Asynchronously create the ShortCodeInstance - @property - def date_created(self): + :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 """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + + 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]: """ - return self._properties['date_created'] + 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 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 ISO 8601 date and time in GMT when the resource was last 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[ShortCodeInstance]: """ - return self._properties['date_updated'] + 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 short_code(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 short code's 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[ShortCodeInstance]: """ - return self._properties['short_code'] + 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 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: The ISO Country Code - :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[ShortCodeInstance]: """ - return self._properties['iso_country'] + 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. - @property - def capabilities(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 capabilities of the short 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, + ) -> ShortCodePage: """ - return self._properties['capabilities'] + Retrieve a single page of ShortCodeInstance 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 ShortCodeInstance """ - :returns: The absolute URL of the ShortCode 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 = 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: """ - return self._properties['url'] + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately - @property - def is_reserved(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 ShortCodeInstance """ - :returns: Whether the short code should be reserved for manual assignment to participants only - :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 ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: """ - return self._properties['is_reserved'] + 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 delete(self): + :returns: Page of ShortCodeInstance """ - Deletes the ShortCodeInstance + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> ShortCodePage: """ - return self._proxy.delete() + Asynchronously retrieve a specific page of ShortCodeInstance 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 ShortCodeInstance """ - Fetch the ShortCodeInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) - :returns: The fetched ShortCodeInstance - :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance + def get(self, sid: str) -> ShortCodeContext: """ - return self._proxy.fetch() + Constructs a ShortCodeContext - def update(self, is_reserved=values.unset): + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. """ - Update the ShortCodeInstance + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - :param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext - :returns: The updated 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.update(is_reserved=is_reserved, ) + 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 index 5fcdd8b97c..a9f32edb0f 100644 --- a/twilio/rest/serverless/__init__.py +++ b/twilio/rest/serverless/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.serverless.v1 import V1 +from twilio.rest.serverless.ServerlessBase import ServerlessBase +from twilio.rest.serverless.v1.service import ServiceList -class Serverless(Domain): - - def __init__(self, twilio): - """ - Initialize the Serverless Domain - - :returns: Domain for Serverless - :rtype: twilio.rest.serverless.Serverless - """ - super(Serverless, self).__init__(twilio) - - self.base_url = 'https://serverless.twilio.com' - - # Versions - self._v1 = None - +class Serverless(ServerlessBase): @property - def v1(self): - """ - :returns: Version v1 of serverless - :rtype: twilio.rest.serverless.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 - - @property - def services(self): - """ - :rtype: twilio.rest.serverless.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/serverless/v1/__init__.py b/twilio/rest/serverless/v1/__init__.py index 6f4d5cbe95..e494615caf 100644 --- a/twilio/rest/serverless/v1/__init__.py +++ b/twilio/rest/serverless/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Serverless - :returns: V1 version of Serverless - :rtype: twilio.rest.serverless.v1.V1.V1 + :param domain: The Twilio.serverless 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.serverless.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/serverless/v1/service/__init__.py b/twilio/rest/serverless/v1/service/__init__.py index 15e0631ff4..f6e4e5841e 100644 --- a/twilio/rest/serverless/v1/service/__init__.py +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -1,16 +1,24 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.serverless.v1.service.asset import AssetList from twilio.rest.serverless.v1.service.build import BuildList @@ -18,535 +26,717 @@ from twilio.rest.serverless.v1.service.function import FunctionList -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. """ +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 - def __init__(self, version): + @property + def _proxy(self) -> "ServiceContext": """ - Initialize the ServiceList + 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: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: twilio.rest.serverless.v1.service.ServiceList - :rtype: twilio.rest.serverless.v1.service.ServiceList + def delete(self) -> bool: """ - super(ServiceList, self).__init__(version) + Deletes the ServiceInstance - # Path Solution - self._solution = {} - self._uri = '/Services'.format(**self._solution) - 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.serverless.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']) + :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.serverless.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.serverless.v1.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + return await self._proxy.fetch_async() - return ServicePage(self._version, response, self._solution) - - def get_page(self, target_url): + 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": """ - 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 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: Page of ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, ) - return ServicePage(self._version, response, self._solution) - - def create(self, unique_name, friendly_name, include_credentials=values.unset, - ui_editable=values.unset): + 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": """ - Create the ServiceInstance + Asynchronous coroutine to update the ServiceInstance - :param unicode unique_name: An application-defined string that uniquely identifies the Service resource - :param unicode friendly_name: A string to describe the Service resource - :param bool include_credentials: Whether to inject Account credentials into a function invocation context - :param bool ui_editable: Whether the Service's properties and subresources can be edited via the UI + :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 created ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance + :returns: The updated ServiceInstance """ - data = values.of({ - 'UniqueName': unique_name, - 'FriendlyName': friendly_name, - 'IncludeCredentials': include_credentials, - 'UiEditable': ui_editable, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return ServiceInstance(self._version, payload, ) + return await self._proxy.update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) - def get(self, sid): + @property + def assets(self) -> AssetList: """ - Constructs a ServiceContext - - :param sid: The SID of the Service resource to fetch - - :returns: twilio.rest.serverless.v1.service.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + Access the assets """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.assets - def __call__(self, sid): + @property + def builds(self) -> BuildList: """ - Constructs a ServiceContext + Access the builds + """ + return self._proxy.builds - :param sid: The SID of the Service resource to fetch + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + return self._proxy.environments - :returns: twilio.rest.serverless.v1.service.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + @property + def functions(self) -> FunctionList: + """ + Access the functions """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.functions - 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 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 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.serverless.v1.service.ServicePage - :rtype: twilio.rest.serverless.v1.service.ServicePage + :param version: Version that contains the resource + :param sid: The `sid` or `unique_name` 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._assets: Optional[AssetList] = None + self._builds: Optional[BuildList] = None + self._environments: Optional[EnvironmentList] = None + self._functions: Optional[FunctionList] = None - :returns: twilio.rest.serverless.v1.service.ServiceInstance - :rtype: twilio.rest.serverless.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 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 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 of the Service resource to fetch - :returns: twilio.rest.serverless.v1.service.ServiceContext - :rtype: twilio.rest.serverless.v1.service.ServiceContext + :returns: True if delete succeeds, False otherwise """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._environments = None - self._functions = None - self._assets = None - self._builds = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ServiceInstance: """ Fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def delete(self): + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: """ - Deletes the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ServiceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, include_credentials=values.unset, friendly_name=values.unset, - ui_editable=values.unset): + 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 bool include_credentials: Whether to inject Account credentials into a function invocation context - :param unicode friendly_name: A string to describe the Service resource - :param bool ui_editable: Whether the Service's properties and subresources can be edited via the UI + :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 - :rtype: twilio.rest.serverless.v1.service.ServiceInstance """ - data = values.of({ - 'IncludeCredentials': include_credentials, - 'FriendlyName': friendly_name, - 'UiEditable': ui_editable, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def environments(self): - """ - Access the environments + headers["Accept"] = "application/json" - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList - """ - if self._environments is None: - self._environments = EnvironmentList(self._version, service_sid=self._solution['sid'], ) - return self._environments + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def functions(self): + 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: """ - Access the functions + 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: twilio.rest.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + :returns: The updated ServiceInstance """ - if self._functions is None: - self._functions = FunctionList(self._version, service_sid=self._solution['sid'], ) - return self._functions + + 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): + def assets(self) -> AssetList: """ Access the assets - - :returns: twilio.rest.serverless.v1.service.asset.AssetList - :rtype: twilio.rest.serverless.v1.service.asset.AssetList """ if self._assets is None: - self._assets = AssetList(self._version, service_sid=self._solution['sid'], ) + self._assets = AssetList( + self._version, + self._solution["sid"], + ) return self._assets @property - def builds(self): + def builds(self) -> BuildList: """ Access the builds - - :returns: twilio.rest.serverless.v1.service.build.BuildList - :rtype: twilio.rest.serverless.v1.service.build.BuildList """ if self._builds is None: - self._builds = BuildList(self._version, service_sid=self._solution['sid'], ) + self._builds = BuildList( + self._version, + self._solution["sid"], + ) return self._builds - def __repr__(self): + @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 - :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 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.serverless.v1.service.ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'unique_name': payload.get('unique_name'), - 'include_credentials': payload.get('include_credentials'), - 'ui_editable': payload.get('ui_editable'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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.serverless.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 unique string that identifies the Service resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Service resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the Service resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the Service resource - :rtype: unicode - """ - return self._properties['unique_name'] +class ServiceList(ListResource): - @property - def include_credentials(self): - """ - :returns: Whether to inject Account credentials into a function invocation context - :rtype: bool + def __init__(self, version: Version): """ - return self._properties['include_credentials'] + Initialize the ServiceList + + :param version: Version that contains the resource - @property - def ui_editable(self): """ - :returns: Whether the Service's properties and subresources can be edited via the UI - :rtype: bool + 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: """ - return self._properties['ui_editable'] + Create the ServiceInstance - @property - def date_created(self): + :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 """ - :returns: The ISO 8601 date and time in GMT when the Service resource was created - :rtype: datetime + + 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: """ - return self._properties['date_created'] + Asynchronously create the ServiceInstance - @property - def date_updated(self): + :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 """ - :returns: The ISO 8601 date and time in GMT when the Service resource was last updated - :rtype: datetime + + 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]: """ - return self._properties['date_updated'] + 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 absolute URL of the Service resource - :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 URLs of the Service's nested resources - :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. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 fetch(self): + :returns: list that will contain up to limit results """ - Fetch the ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: The fetched ServiceInstance - :rtype: twilio.rest.serverless.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, include_credentials=values.unset, friendly_name=values.unset, - ui_editable=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 bool include_credentials: Whether to inject Account credentials into a function invocation context - :param unicode friendly_name: A string to describe the Service resource - :param bool ui_editable: Whether the Service's properties and subresources can be edited via the UI + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The updated ServiceInstance - :rtype: twilio.rest.serverless.v1.service.ServiceInstance + :returns: Page of ServiceInstance """ - return self._proxy.update( - include_credentials=include_credentials, - friendly_name=friendly_name, - ui_editable=ui_editable, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - @property - def environments(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 environments + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.environments + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def functions(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the functions + 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.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + :returns: Page of ServiceInstance """ - return self._proxy.functions + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def assets(self): + def get(self, sid: str) -> ServiceContext: """ - Access the assets + Constructs a ServiceContext - :returns: twilio.rest.serverless.v1.service.asset.AssetList - :rtype: twilio.rest.serverless.v1.service.asset.AssetList + :param sid: The `sid` or `unique_name` of the Service resource to update. """ - return self._proxy.assets + return ServiceContext(self._version, sid=sid) - @property - def builds(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the builds + Constructs a ServiceContext - :returns: twilio.rest.serverless.v1.service.build.BuildList - :rtype: twilio.rest.serverless.v1.service.build.BuildList + :param sid: The `sid` or `unique_name` of the Service resource to update. """ - return self._proxy.builds + 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/serverless/v1/service/asset/__init__.py b/twilio/rest/serverless/v1/service/asset/__init__.py index 01cf8f72c4..de68b969be 100644 --- a/twilio/rest/serverless/v1/service/asset/__init__.py +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -1,460 +1,649 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.serverless.v1.service.asset.asset_version import AssetVersionList -class AssetList(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 AssetList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Asset resource is associated with + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssetContext] = None - :returns: twilio.rest.serverless.v1.service.asset.AssetList - :rtype: twilio.rest.serverless.v1.service.asset.AssetList + @property + def _proxy(self) -> "AssetContext": """ - super(AssetList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Assets'.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: AssetContext for this 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 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 = AssetContext( + 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.serverless.v1.service.asset.AssetInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the AssetInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 AssetInstance 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 AssetInstance - :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.serverless.v1.service.asset.AssetInstance] + :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) -> "AssetInstance": """ - Retrieve a single page of AssetInstance records from the API. - Request is executed immediately + Fetch the AssetInstance - :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 AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetPage + :returns: The fetched AssetInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return AssetPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "AssetInstance": """ - Retrieve a specific page of AssetInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the AssetInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetPage + :returns: The fetched AssetInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return AssetPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, friendly_name): + def update(self, friendly_name: str) -> "AssetInstance": """ - Create the AssetInstance + Update the AssetInstance - :param unicode friendly_name: A string to describe the Asset resource + :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 - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + :returns: The updated AssetInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return AssetInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return self._proxy.update( + friendly_name=friendly_name, + ) - def get(self, sid): + async def update_async(self, friendly_name: str) -> "AssetInstance": """ - Constructs a AssetContext + Asynchronous coroutine to update the AssetInstance - :param sid: The SID that identifies the Asset resource to fetch + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. - :returns: twilio.rest.serverless.v1.service.asset.AssetContext - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + :returns: The updated AssetInstance """ - return AssetContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def asset_versions(self) -> AssetVersionList: """ - Constructs a AssetContext - - :param sid: The SID that identifies the Asset resource to fetch - - :returns: twilio.rest.serverless.v1.service.asset.AssetContext - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + Access the asset_versions """ - return AssetContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.asset_versions - 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 AssetPage(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 AssetContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the AssetPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Asset resource is associated with + Initialize the AssetContext - :returns: twilio.rest.serverless.v1.service.asset.AssetPage - :rtype: twilio.rest.serverless.v1.service.asset.AssetPage + :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(AssetPage, 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}/Assets/{sid}".format(**self._solution) - def get_instance(self, payload): + self._asset_versions: Optional[AssetVersionList] = None + + def delete(self) -> bool: """ - Build an instance of AssetInstance + Deletes the AssetInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.serverless.v1.service.asset.AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + :returns: True if delete succeeds, False otherwise """ - return AssetInstance(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 AssetInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class AssetContext(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, service_sid, sid): + def fetch(self) -> AssetInstance: """ - Initialize the AssetContext + Fetch the AssetInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the Asset resource from - :param sid: The SID that identifies the Asset resource to fetch - :returns: twilio.rest.serverless.v1.service.asset.AssetContext - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + :returns: The fetched AssetInstance """ - super(AssetContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Assets/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._asset_versions = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch the AssetInstance + Asynchronous coroutine to fetch the AssetInstance + :returns: The fetched AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, friendly_name: str) -> AssetInstance: """ - Deletes the AssetInstance + Update the AssetInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=self._uri, ) - def update(self, 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( + 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: """ - Update the AssetInstance + Asynchronous coroutine to update the AssetInstance - :param unicode friendly_name: A string to describe the Asset resource + :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 - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def asset_versions(self): + def asset_versions(self) -> AssetVersionList: """ Access the asset_versions - - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList """ if self._asset_versions is None: self._asset_versions = AssetVersionList( self._version, - service_sid=self._solution['service_sid'], - asset_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._asset_versions - 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 AssetInstance(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 AssetPage(Page): - def __init__(self, version, payload, service_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: """ - Initialize the AssetInstance + Build an instance of AssetInstance - :returns: twilio.rest.serverless.v1.service.asset.AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + :param payload: Payload response from the API """ - super(AssetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - # Context - self._context = None - self._solution = {'service_sid': service_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: AssetContext for this AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetContext + +class AssetList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = AssetContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the AssetList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset resources from. - @property - def sid(self): """ - :returns: The unique string that identifies the Asset resource - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the AssetInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the Asset resource - :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 = 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: """ - return self._properties['account_sid'] + Asynchronously create the AssetInstance - @property - def service_sid(self): + :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 """ - :returns: The SID of the Service that the Asset resource is associated with - :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 AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetInstance]: """ - return self._properties['service_sid'] + 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. - @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 string that you assigned to describe the Asset resource - :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[AssetInstance]: """ - return self._properties['friendly_name'] + 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. - @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 ISO 8601 date and time in GMT when the Asset resource 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[AssetInstance]: """ - return self._properties['date_created'] + Lists AssetInstance 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 ISO 8601 date and time in GMT when the Asset resource 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[AssetInstance]: """ - return self._properties['date_updated'] + 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. - @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 absolute URL of the Asset resource - :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, + ) -> AssetPage: """ - return self._properties['url'] + Retrieve a single page of AssetInstance 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 AssetInstance """ - :returns: The links to the nested resources of the asset - :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 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: """ - return self._properties['links'] + 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 - def fetch(self): + :returns: Page of AssetInstance """ - Fetch the AssetInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + headers = values.of({"Content-Type": "application/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: """ - return self._proxy.fetch() + Retrieve a specific page of AssetInstance 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 AssetInstance """ - Deletes the AssetInstance + response = self._version.domain.twilio.request("GET", target_url) + return AssetPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> AssetPage: """ - return self._proxy.delete() + 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 - def update(self, friendly_name): + :returns: Page of AssetInstance """ - Update the AssetInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetPage(self._version, response, self._solution) - :param unicode friendly_name: A string to describe the Asset resource + def get(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext - :returns: The updated AssetInstance - :rtype: twilio.rest.serverless.v1.service.asset.AssetInstance + :param sid: The SID that identifies the Asset resource to update. """ - return self._proxy.update(friendly_name, ) + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def asset_versions(self): + def __call__(self, sid: str) -> AssetContext: """ - Access the asset_versions + Constructs a AssetContext - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList + :param sid: The SID that identifies the Asset resource to update. """ - return self._proxy.asset_versions + return AssetContext( + 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/serverless/v1/service/asset/asset_version.py b/twilio/rest/serverless/v1/service/asset/asset_version.py index bbe9f6b3e9..31f85d4c29 100644 --- a/twilio/rest/serverless/v1/service/asset/asset_version.py +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -1,395 +1,468 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 AssetVersionList(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 AssetVersionInstance(InstanceResource): - def __init__(self, version, service_sid, asset_sid): - """ - Initialize the AssetVersionList + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Asset Version resource is associated with - :param asset_sid: The SID of the Asset resource that is the parent of the asset version + """ + :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") - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionList + 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": """ - super(AssetVersionList, 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, 'asset_sid': asset_sid, } - self._uri = '/Services/{service_sid}/Assets/{asset_sid}/Versions'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the AssetVersionInstance - :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.serverless.v1.service.asset.asset_version.AssetVersionInstance] + :returns: The fetched AssetVersionInstance """ - 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) -> "AssetVersionInstance": + """ + Asynchronous coroutine to fetch the AssetVersionInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.serverless.v1.service.asset.asset_version.AssetVersionInstance] + 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 AssetVersionInstance 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 AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage +class AssetVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the AssetVersionContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return AssetVersionPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> AssetVersionInstance: """ - Retrieve a specific page of AssetVersionInstance records from the API. - Request is executed immediately + Fetch the AssetVersionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage + :returns: The fetched AssetVersionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return AssetVersionPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a AssetVersionContext + headers["Accept"] = "application/json" - :param sid: The SID that identifies the Asset Version resource to fetch + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext - """ - return AssetVersionContext( + return AssetVersionInstance( self._version, - service_sid=self._solution['service_sid'], - asset_sid=self._solution['asset_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> AssetVersionInstance: """ - Constructs a AssetVersionContext + Asynchronous coroutine to fetch the AssetVersionInstance - :param sid: The SID that identifies the Asset Version resource to fetch - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext + :returns: The fetched AssetVersionInstance """ - return AssetVersionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssetVersionInstance( self._version, - service_sid=self._solution['service_sid'], - asset_sid=self._solution['asset_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_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 AssetVersionPage(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 AssetVersionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Asset Version resource is associated with - :param asset_sid: The SID of the Asset resource that is the parent of the asset version - - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionPage - """ - super(AssetVersionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: """ Build an instance of AssetVersionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.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'], + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class AssetVersionContext(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 AssetVersionList(ListResource): - def __init__(self, version, service_sid, asset_sid, sid): + def __init__(self, version: Version, service_sid: str, asset_sid: str): """ - Initialize the AssetVersionContext + Initialize the AssetVersionList - :param Version 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 that identifies the Asset Version resource to fetch + :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. - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext """ - super(AssetVersionContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + } + self._uri = "/Services/{service_sid}/Assets/{asset_sid}/Versions".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetVersionInstance]: """ - Fetch the 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. - :returns: The fetched AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return AssetVersionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - asset_sid=self._solution['asset_sid'], - sid=self._solution['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[AssetVersionInstance]: """ - Provide a friendly representation + 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. - :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 AssetVersionInstance(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 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. - class Visibility(object): - PUBLIC = "public" - PRIVATE = "private" - PROTECTED = "protected" + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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, service_sid, asset_sid, sid=None): + :returns: list that will contain up to limit results """ - Initialize the AssetVersionInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: """ - super(AssetVersionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'asset_sid': payload.get('asset_sid'), - 'path': payload.get('path'), - 'visibility': payload.get('visibility'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'asset_sid': asset_sid, - 'sid': sid or self._properties['sid'], - } + 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. - @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 + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: AssetVersionContext for this AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext + :returns: list that will contain up to limit results """ - 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 [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, ) - return self._context + ] - @property - def sid(self): - """ - :returns: The unique string that identifies the Asset Version resource - :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, + ) -> AssetVersionPage: """ - return self._properties['sid'] + Retrieve a single page of AssetVersionInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Asset Version resource - :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 service_sid(self): - """ - :returns: The SID of the Service that the Asset Version resource is associated with - :rtype: unicode + :returns: Page of AssetVersionInstance """ - return self._properties['service_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def asset_sid(self): - """ - :returns: The SID of the Asset resource that is the parent of the asset version - :rtype: unicode - """ - return self._properties['asset_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def path(self): + 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: """ - :returns: The URL-friendly string by which the asset version can be referenced - :rtype: unicode + 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 """ - return self._properties['path'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def visibility(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 AssetVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssetVersionPage: """ - :returns: The access control that determines how the asset version can be accessed - :rtype: AssetVersionInstance.Visibility + 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 """ - return self._properties['visibility'] + response = self._version.domain.twilio.request("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) - @property - def date_created(self): + async def get_page_async(self, target_url: str) -> AssetVersionPage: """ - :returns: The ISO 8601 date and time in GMT when the Asset Version resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> AssetVersionContext: """ - :returns: The absolute URL of the Asset Version resource - :rtype: unicode + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. """ - return self._properties['url'] + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> AssetVersionContext: """ - Fetch the AssetVersionInstance + Constructs a AssetVersionContext - :returns: The fetched AssetVersionInstance - :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance + :param sid: The SID of the Asset Version resource to fetch. """ - return self._proxy.fetch() + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_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/serverless/v1/service/build.py b/twilio/rest/serverless/v1/service/build.py deleted file mode 100644 index 829312e48b..0000000000 --- a/twilio/rest/serverless/v1/service/build.py +++ /dev/null @@ -1,430 +0,0 @@ -# coding=utf-8 -r""" -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 BuildList(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 BuildList - - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Build resource is associated with - - :returns: twilio.rest.serverless.v1.service.build.BuildList - :rtype: twilio.rest.serverless.v1.service.build.BuildList - """ - super(BuildList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Builds'.format(**self._solution) - - def stream(self, limit=None, page_size=None): - """ - 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 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.serverless.v1.service.build.BuildInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, limit=None, page_size=None): - """ - 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 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.serverless.v1.service.build.BuildInstance] - """ - 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 BuildInstance 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 BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return BuildPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of BuildInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return BuildPage(self._version, response, self._solution) - - def create(self, asset_versions=values.unset, function_versions=values.unset, - dependencies=values.unset): - """ - Create the BuildInstance - - :param unicode asset_versions: The list of Asset Version resource SIDs to include in the build - :param unicode function_versions: The list of the Variable resource SIDs to include in the build - :param unicode dependencies: A list of objects that describe the Dependencies included in the build - - :returns: The created BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildInstance - """ - data = values.of({ - 'AssetVersions': serialize.map(asset_versions, lambda e: e), - 'FunctionVersions': serialize.map(function_versions, lambda e: e), - 'Dependencies': dependencies, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return BuildInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def get(self, sid): - """ - Constructs a BuildContext - - :param sid: The SID of the Build resource to fetch - - :returns: twilio.rest.serverless.v1.service.build.BuildContext - :rtype: twilio.rest.serverless.v1.service.build.BuildContext - """ - return BuildContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) - - def __call__(self, sid): - """ - Constructs a BuildContext - - :param sid: The SID of the Build resource to fetch - - :returns: twilio.rest.serverless.v1.service.build.BuildContext - :rtype: twilio.rest.serverless.v1.service.build.BuildContext - """ - return BuildContext(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 BuildPage(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 BuildPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Build resource is associated with - - :returns: twilio.rest.serverless.v1.service.build.BuildPage - :rtype: twilio.rest.serverless.v1.service.build.BuildPage - """ - super(BuildPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of BuildInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.build.BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildInstance - """ - return BuildInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class BuildContext(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 BuildContext - - :param Version 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 - - :returns: twilio.rest.serverless.v1.service.build.BuildContext - :rtype: twilio.rest.serverless.v1.service.build.BuildContext - """ - super(BuildContext, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Builds/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the BuildInstance - - :returns: The fetched BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return BuildInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the BuildInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 BuildInstance(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): - BUILDING = "building" - COMPLETED = "completed" - FAILED = "failed" - - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the BuildInstance - - :returns: twilio.rest.serverless.v1.service.build.BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildInstance - """ - super(BuildInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'status': payload.get('status'), - 'asset_versions': payload.get('asset_versions'), - 'function_versions': payload.get('function_versions'), - 'dependencies': payload.get('dependencies'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: BuildContext for this BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildContext - """ - if self._context is None: - self._context = BuildContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context - - @property - def sid(self): - """ - :returns: The unique string that identifies the Build resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Build resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def service_sid(self): - """ - :returns: The SID of the Service that the Build resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - - @property - def status(self): - """ - :returns: The status of the build - :rtype: BuildInstance.Status - """ - return self._properties['status'] - - @property - def asset_versions(self): - """ - :returns: The list of Asset Version resource SIDs that are included in the build - :rtype: dict - """ - return self._properties['asset_versions'] - - @property - def function_versions(self): - """ - :returns: The list of Function Version resource SIDs that are included in the build - :rtype: dict - """ - return self._properties['function_versions'] - - @property - def dependencies(self): - """ - :returns: A list of objects that describe the Dependencies included in the build - :rtype: dict - """ - return self._properties['dependencies'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Build resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the Build resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The absolute URL of the Build resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the BuildInstance - - :returns: The fetched BuildInstance - :rtype: twilio.rest.serverless.v1.service.build.BuildInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the BuildInstance - - :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/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 index 51c641e726..cdad0504a7 100644 --- a/twilio/rest/serverless/v1/service/environment/__init__.py +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -1,513 +1,623 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.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 EnvironmentList(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 EnvironmentList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Environment resource is associated with + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[EnvironmentContext] = None - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList + @property + def _proxy(self) -> "EnvironmentContext": """ - super(EnvironmentList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Environments'.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: EnvironmentContext for this 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 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 = EnvironmentContext( + 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.serverless.v1.service.environment.EnvironmentInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the EnvironmentInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 EnvironmentInstance 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 EnvironmentInstance - :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.serverless.v1.service.environment.EnvironmentInstance] + :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) -> "EnvironmentInstance": """ - Retrieve a single page of EnvironmentInstance records from the API. - Request is executed immediately + Fetch the EnvironmentInstance - :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 EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentPage + :returns: The fetched EnvironmentInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return EnvironmentPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "EnvironmentInstance": """ - Retrieve a specific page of EnvironmentInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the EnvironmentInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentPage + :returns: The fetched EnvironmentInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EnvironmentPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, unique_name, domain_suffix=values.unset): + @property + def deployments(self) -> DeploymentList: """ - Create the EnvironmentInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the Environment resource - :param unicode domain_suffix: A URL-friendly name that represents the environment - - :returns: The created EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance + Access the deployments """ - data = values.of({'UniqueName': unique_name, 'DomainSuffix': domain_suffix, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return EnvironmentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return self._proxy.deployments - def get(self, sid): + @property + def logs(self) -> LogList: """ - Constructs a EnvironmentContext - - :param sid: The SID of the Environment resource to fetch - - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + Access the logs """ - return EnvironmentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.logs - def __call__(self, sid): + @property + def variables(self) -> VariableList: """ - Constructs a EnvironmentContext - - :param sid: The SID of the Environment resource to fetch - - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + Access the variables """ - return EnvironmentContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.variables - 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 EnvironmentPage(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 EnvironmentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the EnvironmentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Environment resource is associated with + Initialize the EnvironmentContext - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentPage - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentPage + :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(EnvironmentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of EnvironmentInstance + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{sid}".format( + **self._solution + ) - :param dict payload: Payload response from the API + self._deployments: Optional[DeploymentList] = None + self._logs: Optional[LogList] = None + self._variables: Optional[VariableList] = None - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance + def delete(self) -> bool: """ - return EnvironmentInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the EnvironmentInstance - 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 EnvironmentContext(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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the EnvironmentContext + Asynchronous coroutine that deletes the EnvironmentInstance - :param Version 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 - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + :returns: True if delete succeeds, False otherwise """ - super(EnvironmentContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Environments/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._variables = None - self._deployments = None - self._logs = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> EnvironmentInstance: """ Fetch the EnvironmentInstance + :returns: The fetched EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> EnvironmentInstance: """ - Deletes the EnvironmentInstance + Asynchronous coroutine to fetch the EnvironmentInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - @property - def variables(self): + :returns: The fetched EnvironmentInstance """ - Access the variables - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList - """ - if self._variables is None: - self._variables = VariableList( - self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['sid'], - ) - return self._variables + 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): + def deployments(self) -> DeploymentList: """ Access the deployments - - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList """ if self._deployments is None: self._deployments = DeploymentList( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._deployments @property - def logs(self): + def logs(self) -> LogList: """ Access the logs - - :returns: twilio.rest.serverless.v1.service.environment.log.LogList - :rtype: twilio.rest.serverless.v1.service.environment.log.LogList """ if self._logs is None: self._logs = LogList( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._logs - def __repr__(self): + @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 - :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 EnvironmentInstance(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 EnvironmentInstance - - :returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance - """ - super(EnvironmentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'build_sid': payload.get('build_sid'), - 'unique_name': payload.get('unique_name'), - 'domain_suffix': payload.get('domain_suffix'), - 'domain_name': payload.get('domain_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class EnvironmentPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: """ - 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 EnvironmentInstance - :returns: EnvironmentContext for this EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = EnvironmentContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def sid(self): + def __repr__(self) -> str: """ - :returns: The unique string that identifies the Environment resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Environment resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def service_sid(self): - """ - :returns: The SID of the Service that the Environment resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] - @property - def build_sid(self): +class EnvironmentList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The SID of the build deployed in the environment - :rtype: unicode + Initialize the EnvironmentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Environment resources from. + """ - return self._properties['build_sid'] + super().__init__(version) - @property - def unique_name(self): + # 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: """ - :returns: An application-defined string that uniquely identifies the Environment resource - :rtype: unicode + 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 """ - return self._properties['unique_name'] - @property - def domain_suffix(self): + 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: """ - :returns: A URL-friendly name that represents the environment - :rtype: unicode + 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 """ - return self._properties['domain_suffix'] - @property - def domain_name(self): + 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]: """ - :returns: The base domain name for all Functions and Assets deployed in the environment - :rtype: unicode + 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 """ - return self._properties['domain_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[EnvironmentInstance]: """ - :returns: The ISO 8601 date and time in GMT when the Environment resource was created - :rtype: datetime + 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 """ - 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[EnvironmentInstance]: """ - :returns: The ISO 8601 date and time in GMT when the Environment resource was last updated - :rtype: datetime + 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 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[EnvironmentInstance]: """ - :returns: The absolute URL of the Environment resource - :rtype: unicode + 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 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, + ) -> EnvironmentPage: """ - :returns: The URLs of the environment's nested resources - :rtype: unicode + 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 """ - 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"}) - def fetch(self): + 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: """ - Fetch the EnvironmentInstance + Asynchronously retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately - :returns: The fetched EnvironmentInstance - :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 EnvironmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EnvironmentPage: """ - Deletes the EnvironmentInstance + Retrieve a specific page of EnvironmentInstance 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 EnvironmentInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) - @property - def variables(self): + async def get_page_async(self, target_url: str) -> EnvironmentPage: """ - Access the variables + Asynchronously retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance """ - return self._proxy.variables + response = await self._version.domain.twilio.request_async("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) - @property - def deployments(self): + def get(self, sid: str) -> EnvironmentContext: """ - Access the deployments + Constructs a EnvironmentContext - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList + :param sid: The SID of the Environment resource to fetch. """ - return self._proxy.deployments + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def logs(self): + def __call__(self, sid: str) -> EnvironmentContext: """ - Access the logs + Constructs a EnvironmentContext - :returns: twilio.rest.serverless.v1.service.environment.log.LogList - :rtype: twilio.rest.serverless.v1.service.environment.log.LogList + :param sid: The SID of the Environment resource to fetch. """ - return self._proxy.logs + return EnvironmentContext( + 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/serverless/v1/service/environment/deployment.py b/twilio/rest/serverless/v1/service/environment/deployment.py index cf1751797d..d28a4b8db1 100644 --- a/twilio/rest/serverless/v1/service/environment/deployment.py +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -1,410 +1,540 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 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, service_sid, environment_sid): - """ - Initialize the DeploymentList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Deployment resource is associated with - :param environment_sid: The SID of the environment for the deployment + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeploymentContext] = None - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList + @property + def _proxy(self) -> "DeploymentContext": """ - super(DeploymentList, self).__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) + 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: DeploymentContext for this 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 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 = DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance] + def fetch(self) -> "DeploymentInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the DeploymentInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched DeploymentInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the DeploymentInstance - :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.serverless.v1.service.environment.deployment.DeploymentInstance] + :returns: The fetched DeploymentInstance """ - 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 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 + Provide a friendly representation - :returns: Page of DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage + :returns: Machine friendly representation """ - data = 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(method='GET', uri=self._uri, params=data, ) - return DeploymentPage(self._version, response, self._solution) +class DeploymentContext(InstanceContext): - def get_page(self, target_url): + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): """ - 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 + Initialize the DeploymentContext - :returns: Page of DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return DeploymentPage(self._version, response, self._solution) + # 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 create(self, build_sid=values.unset): + def fetch(self) -> DeploymentInstance: """ - Create the DeploymentInstance + Fetch the DeploymentInstance - :param unicode build_sid: The SID of the build for the deployment - :returns: The created DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + :returns: The fetched DeploymentInstance """ - data = values.of({'BuildSid': build_sid, }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> DeploymentInstance: """ - Constructs a DeploymentContext + Asynchronous coroutine to fetch the DeploymentInstance - :param sid: The SID that identifies the Deployment resource to fetch - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext + :returns: The fetched DeploymentInstance """ - return DeploymentContext( - self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, - ) - def __call__(self, sid): - """ - Constructs a DeploymentContext + headers = values.of({}) - :param sid: The SID that identifies the Deployment resource to fetch + headers["Accept"] = "application/json" - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext - """ - return DeploymentContext( + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeploymentInstance( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_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 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 service_sid: The SID of the Service that the Deployment resource is associated with - :param environment_sid: The SID of the environment for the deployment - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentPage - """ - super(DeploymentPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: """ Build an instance of DeploymentInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.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'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + 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. """ +class DeploymentList(ListResource): - def __init__(self, version, service_sid, environment_sid, sid): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ - Initialize the DeploymentContext + Initialize the DeploymentList - :param Version 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 + :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. - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext """ - super(DeploymentContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Deployments".format( + **self._solution + ) + ) - def fetch(self): + def create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: """ - Fetch the DeploymentInstance + Create the DeploymentInstance - :returns: The fetched DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def __repr__(self): + async def create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: """ - Provide a friendly representation + Asynchronously create the DeploymentInstance - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + :returns: The created DeploymentInstance + """ -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. """ + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __init__(self, version, payload, service_sid, environment_sid, sid=None): - """ - Initialize the DeploymentInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance - """ - super(DeploymentInstance, self).__init__(version) + headers["Accept"] = "application/json" - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'environment_sid': payload.get('environment_sid'), - 'build_sid': payload.get('build_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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, - 'environment_sid': environment_sid, - 'sid': sid or self._properties['sid'], - } + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeploymentInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: DeploymentContext for this DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = DeploymentContext( - self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=self._solution['sid'], - ) - return self._context + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeploymentInstance]: """ - :returns: The unique string that identifies the Deployment resource - :rtype: unicode + 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 """ - return self._properties['sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def account_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: """ - :returns: The SID of the Account that created the Deployment resource - :rtype: unicode + 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 self._properties['account_sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def service_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: """ - :returns: The SID of the Service that the Deployment resource is associated with - :rtype: unicode + 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 self._properties['service_sid'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def environment_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, + ) -> DeploymentPage: """ - :returns: The SID of the environment for the deployment - :rtype: unicode + 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 """ - return self._properties['environment_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def build_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 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: """ - :returns: The SID of the build for the deployment - :rtype: unicode + 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 """ - return self._properties['build_sid'] + 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 DeploymentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeploymentPage: """ - :returns: The ISO 8601 date and time in GMT when the Deployment resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return DeploymentPage(self._version, response, self._solution) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> DeploymentPage: """ - :returns: The ISO 8601 date and time in GMT when the Deployment resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeploymentPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> DeploymentContext: """ - :returns: The absolute URL of the Deployment resource - :rtype: unicode + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. """ - return self._properties['url'] + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> DeploymentContext: """ - Fetch the DeploymentInstance + Constructs a DeploymentContext - :returns: The fetched DeploymentInstance - :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentInstance + :param sid: The SID that identifies the Deployment resource to fetch. """ - return self._proxy.fetch() + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_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/serverless/v1/service/environment/log.py b/twilio/rest/serverless/v1/service/environment/log.py index 3dfa7cd294..a3c9a6c2da 100644 --- a/twilio/rest/serverless/v1/service/environment/log.py +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -1,462 +1,538 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 LogList(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 LogInstance(InstanceResource): - def __init__(self, version, service_sid, environment_sid): - """ - Initialize the LogList + class Level(object): + INFO = "info" + WARN = "warn" + ERROR = "error" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Log resource is associated with - :param environment_sid: The SID of the environment in which the log occurred + """ + :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") - :returns: twilio.rest.serverless.v1.service.environment.log.LogList - :rtype: twilio.rest.serverless.v1.service.environment.log.LogList + 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": """ - super(LogList, 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, 'environment_sid': environment_sid, } - self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Logs'.format(**self._solution) + :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 stream(self, function_sid=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the LogInstance - :param unicode function_sid: The SID of the function whose invocation produced the Log resources to read - :param datetime start_date: The date and time after which the Log resources must have been created. - :param datetime end_date: The date and time before which the Log resource must have been 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.environment.log.LogInstance] + :returns: The fetched LogInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page( - function_sid=function_sid, - start_date=start_date, - end_date=end_date, - page_size=limits['page_size'], - ) + async def fetch_async(self) -> "LogInstance": + """ + Asynchronous coroutine to fetch the LogInstance - return self._version.stream(page, limits['limit']) - def list(self, function_sid=values.unset, start_date=values.unset, - end_date=values.unset, limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param unicode function_sid: The SID of the function whose invocation produced the Log resources to read - :param datetime start_date: The date and time after which the Log resources must have been created. - :param datetime end_date: The date and time before which the Log resource must have been 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.serverless.v1.service.environment.log.LogInstance] + def __repr__(self) -> str: """ - return list(self.stream( - function_sid=function_sid, - start_date=start_date, - end_date=end_date, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - def page(self, function_sid=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 LogInstance 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 function_sid: The SID of the function whose invocation produced the Log resources to read - :param datetime start_date: The date and time after which the Log resources must have been created. - :param datetime end_date: The date and time before which the Log resource must have been 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 LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogPage +class LogContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): """ - 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, - }) + Initialize the LogContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return LogPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def fetch(self) -> LogInstance: """ - Retrieve a specific page of LogInstance records from the API. - Request is executed immediately + Fetch the LogInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogPage + :returns: The fetched LogInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return LogPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a LogContext + headers["Accept"] = "application/json" - :param sid: The SID that identifies the Log resource to fetch + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.serverless.v1.service.environment.log.LogContext - :rtype: twilio.rest.serverless.v1.service.environment.log.LogContext - """ - return LogContext( + return LogInstance( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> LogInstance: """ - Constructs a LogContext + Asynchronous coroutine to fetch the LogInstance - :param sid: The SID that identifies the Log resource to fetch - :returns: twilio.rest.serverless.v1.service.environment.log.LogContext - :rtype: twilio.rest.serverless.v1.service.environment.log.LogContext + :returns: The fetched LogInstance """ - return LogContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return LogInstance( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_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 LogPage(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 LogPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Log resource is associated with - :param environment_sid: The SID of the environment in which the log occurred - - :returns: twilio.rest.serverless.v1.service.environment.log.LogPage - :rtype: twilio.rest.serverless.v1.service.environment.log.LogPage - """ - super(LogPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> LogInstance: """ Build an instance of LogInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.environment.log.LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.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'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class LogContext(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 LogList(ListResource): - def __init__(self, version, service_sid, environment_sid, sid): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ - Initialize the LogContext + Initialize the LogList - :param Version 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 that identifies the Log resource to fetch + :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. - :returns: twilio.rest.serverless.v1.service.environment.log.LogContext - :rtype: twilio.rest.serverless.v1.service.environment.log.LogContext """ - super(LogContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs".format( + **self._solution + ) + ) - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + :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) - return LogInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_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( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], ) - def __repr__(self): - """ - Provide a friendly representation + return self._version.stream(page, limits["limit"]) - :returns: Machine friendly representation - :rtype: str + 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]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) - - -class LogInstance(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. """ + 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. - class Level(object): - INFO = "info" - WARN = "warn" - ERROR = "error" + :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) - def __init__(self, version, payload, service_sid, environment_sid, sid=None): - """ - Initialize the LogInstance - - :returns: twilio.rest.serverless.v1.service.environment.log.LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance - """ - super(LogInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'environment_sid': payload.get('environment_sid'), - 'build_sid': payload.get('build_sid'), - 'deployment_sid': payload.get('deployment_sid'), - 'function_sid': payload.get('function_sid'), - 'request_sid': payload.get('request_sid'), - 'level': payload.get('level'), - 'message': payload.get('message'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'url': payload.get('url'), - } + :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"], + ) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'environment_sid': environment_sid, - 'sid': sid or self._properties['sid'], - } + return self._version.stream_async(page, limits["limit"]) - @property - def _proxy(self): + 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]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: LogContext for this LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogContext - """ - 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'], + :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, ) - return self._context + ) - @property - def sid(self): + 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]: """ - :returns: The unique string that identifies the Log resource - :rtype: unicode - """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Log resource - :rtype: unicode + :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: """ - return self._properties['account_sid'] + Retrieve a single page of LogInstance records from the API. + Request is executed immediately - @property - def service_sid(self): - """ - :returns: The SID of the Service that the Log resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + :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 - @property - def environment_sid(self): - """ - :returns: The SID of the environment in which the log occurred - :rtype: unicode + :returns: Page of LogInstance """ - return self._properties['environment_sid'] + 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, + } + ) - @property - def build_sid(self): - """ - :returns: The SID of the build that corresponds to the log - :rtype: unicode - """ - return self._properties['build_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def deployment_sid(self): - """ - :returns: The SID of the deployment that corresponds to the log - :rtype: unicode - """ - return self._properties['deployment_sid'] + headers["Accept"] = "application/json" - @property - def function_sid(self): - """ - :returns: The SID of the function whose invocation produced the log - :rtype: unicode - """ - return self._properties['function_sid'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, self._solution) - @property - def request_sid(self): - """ - :returns: The SID of the request associated with the log - :rtype: unicode - """ - return self._properties['request_sid'] + 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 - @property - def level(self): - """ - :returns: The log level - :rtype: LogInstance.Level + :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 """ - return self._properties['level'] + 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, + } + ) - @property - def message(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 LogPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LogPage: """ - :returns: The log message - :rtype: unicode + 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 """ - return self._properties['message'] + response = self._version.domain.twilio.request("GET", target_url) + return LogPage(self._version, response, self._solution) - @property - def date_created(self): + async def get_page_async(self, target_url: str) -> LogPage: """ - :returns: The ISO 8601 date and time in GMT when the Log resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return LogPage(self._version, response, self._solution) - @property - def url(self): + def get(self, sid: str) -> LogContext: """ - :returns: The absolute URL of the Log resource - :rtype: unicode + Constructs a LogContext + + :param sid: The SID of the Log resource to fetch. """ - return self._properties['url'] + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> LogContext: """ - Fetch the LogInstance + Constructs a LogContext - :returns: The fetched LogInstance - :rtype: twilio.rest.serverless.v1.service.environment.log.LogInstance + :param sid: The SID of the Log resource to fetch. """ - return self._proxy.fetch() + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_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/serverless/v1/service/environment/variable.py b/twilio/rest/serverless/v1/service/environment/variable.py index bcfb821b75..fbc6b48ac8 100644 --- a/twilio/rest/serverless/v1/service/environment/variable.py +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -1,472 +1,690 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 VariableList(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 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 - def __init__(self, version, service_sid, environment_sid): + @property + def _proxy(self) -> "VariableContext": """ - Initialize the VariableList + 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 SID of the Service that the Variable resource is associated with - :param environment_sid: The SID of the environment in which the variable exists + :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 - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableList - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableList + def delete(self) -> bool: """ - super(VariableList, self).__init__(version) + Deletes the VariableInstance - # 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 stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance - :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.serverless.v1.service.environment.variable.VariableInstance] + :returns: True if delete succeeds, False otherwise """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.delete_async() + + def fetch(self) -> "VariableInstance": + """ + Fetch the VariableInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched VariableInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the VariableInstance - :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.serverless.v1.service.environment.variable.VariableInstance] + :returns: The fetched VariableInstance """ - 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, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": """ - Retrieve a single page of VariableInstance records from the API. - Request is executed immediately + Update the VariableInstance - :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 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: Page of VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + :returns: The updated VariableInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return self._proxy.update( + key=key, + value=value, + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Asynchronous coroutine to update the VariableInstance - return VariablePage(self._version, response, self._solution) + :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. - def get_page(self, target_url): + :returns: The updated VariableInstance """ - Retrieve a specific page of VariableInstance records from the API. - Request is executed immediately + return await self._proxy.update_async( + key=key, + value=value, + ) - :param str target_url: API-generated URL for the requested results page + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + :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) + + +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 ) - return VariablePage(self._version, response, self._solution) + def delete(self) -> bool: + """ + Deletes the VariableInstance + - def create(self, key, value): + :returns: True if delete succeeds, False otherwise """ - Create the VariableInstance - :param unicode key: A string by which the Variable resource can be referenced - :param unicode value: A string that contains the actual value of the variable + headers = values.of({}) - :returns: The created VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + 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: """ - data = values.of({'Key': key, 'Value': value, }) + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + + headers = values.of({}) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - def get(self, sid): + async def fetch_async(self) -> VariableInstance: """ - Constructs a VariableContext + Asynchronous coroutine to fetch the VariableInstance - :param sid: The SID of the Variable resource to fetch - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext + :returns: The fetched VariableInstance """ - return VariableContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VariableInstance( self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: """ - Constructs a VariableContext + Update the VariableInstance - :param sid: The SID of the Variable resource to fetch + :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: twilio.rest.serverless.v1.service.environment.variable.VariableContext - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext + :returns: The updated VariableInstance """ - return VariableContext( + + 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, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: """ - Provide a friendly representation + Asynchronous coroutine to update the VariableInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) -class VariablePage(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. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, response, solution): - """ - Initialize the VariablePage + headers["Accept"] = "application/json" - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Variable resource is associated with - :param environment_sid: The SID of the environment in which the variable exists + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.serverless.v1.service.environment.variable.VariablePage - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariablePage + 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: """ - super(VariablePage, 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 VariablePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: """ Build an instance of VariableInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.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'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class VariableContext(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 VariableList(ListResource): - def __init__(self, version, service_sid, environment_sid, sid): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ - Initialize the VariableContext + Initialize the VariableList - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the Variable resource from - :param environment_sid: The SID of the environment with the Variable resource to fetch - :param sid: The SID of the Variable resource to fetch + :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. - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableContext - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext """ - super(VariableContext, self).__init__(version) + 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) + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Variables".format( + **self._solution + ) + ) - def fetch(self): + def create(self, key: str, value: str) -> VariableInstance: """ - Fetch the VariableInstance + Create the VariableInstance - :returns: The fetched VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def update(self, key=values.unset, value=values.unset): + async def create_async(self, key: str, value: str) -> VariableInstance: """ - Update the VariableInstance + Asynchronously create the VariableInstance - :param unicode key: A string by which the Variable resource can be referenced - :param unicode value: A string that contains the actual value of the variable + :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 - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + :returns: The created VariableInstance """ - data = values.of({'Key': key, 'Value': value, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], ) - def delete(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VariableInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VariableInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class VariableInstance(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, environment_sid, sid=None): - """ - Initialize the VariableInstance - - :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance - """ - super(VariableInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'environment_sid': payload.get('environment_sid'), - 'key': payload.get('key'), - 'value': payload.get('value'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + :returns: Generator that 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, - 'environment_sid': environment_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[VariableInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists VariableInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: VariableContext for this VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = VariableContext( - self._version, - service_sid=self._solution['service_sid'], - environment_sid=self._solution['environment_sid'], - sid=self._solution['sid'], + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def sid(self): - """ - :returns: The unique string that identifies the Variable resource - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: """ - return self._properties['sid'] + 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. - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Variable resource - :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 service_sid(self): - """ - :returns: The SID of the Service that the Variable resource is associated with - :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 environment_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, + ) -> VariablePage: """ - :returns: The SID of the environment in which the variable exists - :rtype: unicode - """ - return self._properties['environment_sid'] + Retrieve a single page of VariableInstance records from the API. + Request is executed immediately - @property - def key(self): - """ - :returns: A string by which the Variable resource can be referenced - :rtype: unicode - """ - return self._properties['key'] + :param page_token: PageToken provided by the 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 value(self): - """ - :returns: A string that contains the actual value of the variable - :rtype: unicode + :returns: Page of VariableInstance """ - return self._properties['value'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Variable resource was 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 ISO 8601 date and time in GMT when the Variable resource was last updated - :rtype: datetime + 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of VariableInstance 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 VariableInstance """ - :returns: The absolute URL of the Variable 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 VariablePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> VariablePage: """ - return self._properties['url'] + Retrieve a specific page of VariableInstance 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 VariableInstance """ - Fetch the VariableInstance + response = self._version.domain.twilio.request("GET", target_url) + return VariablePage(self._version, response, self._solution) - :returns: The fetched VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + async def get_page_async(self, target_url: str) -> VariablePage: """ - return self._proxy.fetch() + 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 - def update(self, key=values.unset, value=values.unset): + :returns: Page of VariableInstance """ - Update the VariableInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return VariablePage(self._version, response, self._solution) - :param unicode key: A string by which the Variable resource can be referenced - :param unicode value: A string that contains the actual value of the variable + def get(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext - :returns: The updated VariableInstance - :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance + :param sid: The SID of the Variable resource to update. """ - return self._proxy.update(key=key, value=value, ) + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> VariableContext: """ - Deletes the VariableInstance + Constructs a VariableContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Variable resource to update. """ - return self._proxy.delete() + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_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/serverless/v1/service/function/__init__.py b/twilio/rest/serverless/v1/service/function/__init__.py index b273508bb7..7697587e60 100644 --- a/twilio/rest/serverless/v1/service/function/__init__.py +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -1,460 +1,651 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.serverless.v1.service.function.function_version import FunctionVersionList +from twilio.rest.serverless.v1.service.function.function_version import ( + FunctionVersionList, +) -class FunctionList(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 FunctionList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Function resource is associated with + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionContext] = None - :returns: twilio.rest.serverless.v1.service.function.FunctionList - :rtype: twilio.rest.serverless.v1.service.function.FunctionList + @property + def _proxy(self) -> "FunctionContext": """ - super(FunctionList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Functions'.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: FunctionContext for this 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 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 = FunctionContext( + 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.serverless.v1.service.function.FunctionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the FunctionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 FunctionInstance 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 FunctionInstance - :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.serverless.v1.service.function.FunctionInstance] + :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) -> "FunctionInstance": """ - Retrieve a single page of FunctionInstance records from the API. - Request is executed immediately + Fetch the FunctionInstance - :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 FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionPage + :returns: The fetched FunctionInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return FunctionPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "FunctionInstance": """ - Retrieve a specific page of FunctionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the FunctionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionPage + :returns: The fetched FunctionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return FunctionPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def create(self, friendly_name): + def update(self, friendly_name: str) -> "FunctionInstance": """ - Create the FunctionInstance + Update the FunctionInstance - :param unicode friendly_name: A string to describe the Function resource + :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 - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + :returns: The updated FunctionInstance """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return FunctionInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + return self._proxy.update( + friendly_name=friendly_name, + ) - def get(self, sid): + async def update_async(self, friendly_name: str) -> "FunctionInstance": """ - Constructs a FunctionContext + Asynchronous coroutine to update the FunctionInstance - :param sid: The SID of the Function resource to fetch + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. - :returns: twilio.rest.serverless.v1.service.function.FunctionContext - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + :returns: The updated FunctionInstance """ - return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def function_versions(self) -> FunctionVersionList: """ - Constructs a FunctionContext - - :param sid: The SID of the Function resource to fetch - - :returns: twilio.rest.serverless.v1.service.function.FunctionContext - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + Access the function_versions """ - return FunctionContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.function_versions - 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 FunctionPage(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 FunctionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the FunctionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Function resource is associated with + Initialize the FunctionContext - :returns: twilio.rest.serverless.v1.service.function.FunctionPage - :rtype: twilio.rest.serverless.v1.service.function.FunctionPage + :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(FunctionPage, 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}/Functions/{sid}".format(**self._solution) - def get_instance(self, payload): + self._function_versions: Optional[FunctionVersionList] = None + + def delete(self) -> bool: """ - Build an instance of FunctionInstance + Deletes the FunctionInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.serverless.v1.service.function.FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + :returns: True if delete succeeds, False otherwise """ - return FunctionInstance(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 FunctionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class FunctionContext(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, service_sid, sid): + def fetch(self) -> FunctionInstance: """ - Initialize the FunctionContext + Fetch the FunctionInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service to fetch the Function resource from - :param sid: The SID of the Function resource to fetch - :returns: twilio.rest.serverless.v1.service.function.FunctionContext - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + :returns: The fetched FunctionInstance """ - super(FunctionContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Functions/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._function_versions = None + headers["Accept"] = "application/json" - def fetch(self): + 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: """ - Fetch the FunctionInstance + Asynchronous coroutine to fetch the FunctionInstance + :returns: The fetched FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + def update(self, friendly_name: str) -> FunctionInstance: """ - Deletes the FunctionInstance + Update the FunctionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=self._uri, ) - def update(self, 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( + 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: """ - Update the FunctionInstance + Asynchronous coroutine to update the FunctionInstance - :param unicode friendly_name: A string to describe the Function resource + :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 - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) @property - def function_versions(self): + def function_versions(self) -> FunctionVersionList: """ Access the function_versions - - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList """ if self._function_versions is None: self._function_versions = FunctionVersionList( self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._function_versions - 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 FunctionInstance(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 FunctionPage(Page): - def __init__(self, version, payload, service_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: """ - Initialize the FunctionInstance + Build an instance of FunctionInstance - :returns: twilio.rest.serverless.v1.service.function.FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + :param payload: Payload response from the API """ - super(FunctionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - # Context - self._context = None - self._solution = {'service_sid': service_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: FunctionContext for this FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionContext + +class FunctionList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - if self._context is None: - self._context = FunctionContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the FunctionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function resources from. - @property - def sid(self): """ - :returns: The unique string that identifies the Function resource - :rtype: unicode + 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: """ - return self._properties['sid'] + Create the FunctionInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the Function resource - :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 = 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: """ - return self._properties['account_sid'] + Asynchronously create the FunctionInstance - @property - def service_sid(self): + :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 """ - :returns: The SID of the Service that the Function resource is associated with - :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 FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionInstance]: """ - return self._properties['service_sid'] + 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. - @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 string that you assigned to describe the Function resource - :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[FunctionInstance]: """ - return self._properties['friendly_name'] + 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. - @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 ISO 8601 date and time in GMT when the Function resource 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[FunctionInstance]: """ - return self._properties['date_created'] + Lists FunctionInstance 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 ISO 8601 date and time in GMT when the Function resource 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[FunctionInstance]: """ - return self._properties['date_updated'] + 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. - @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 absolute URL of the Function resource - :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, + ) -> FunctionPage: """ - return self._properties['url'] + Retrieve a single page of FunctionInstance 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 FunctionInstance """ - :returns: The URLs of nested resources of the function - :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 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: """ - return self._properties['links'] + 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 - def fetch(self): + :returns: Page of FunctionInstance """ - Fetch the FunctionInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + headers = values.of({"Content-Type": "application/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: """ - return self._proxy.fetch() + Retrieve a specific page of FunctionInstance 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 FunctionInstance """ - Deletes the FunctionInstance + response = self._version.domain.twilio.request("GET", target_url) + return FunctionPage(self._version, response, self._solution) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def get_page_async(self, target_url: str) -> FunctionPage: """ - return self._proxy.delete() + 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 - def update(self, friendly_name): + :returns: Page of FunctionInstance """ - Update the FunctionInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionPage(self._version, response, self._solution) - :param unicode friendly_name: A string to describe the Function resource + def get(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext - :returns: The updated FunctionInstance - :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance + :param sid: The SID of the Function resource to update. """ - return self._proxy.update(friendly_name, ) + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def function_versions(self): + def __call__(self, sid: str) -> FunctionContext: """ - Access the function_versions + Constructs a FunctionContext - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList + :param sid: The SID of the Function resource to update. """ - return self._proxy.function_versions + return FunctionContext( + 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/serverless/v1/service/function/function_version/__init__.py b/twilio/rest/serverless/v1/service/function/function_version/__init__.py index 226d2c1c29..88b666208c 100644 --- a/twilio/rest/serverless/v1/service/function/function_version/__init__.py +++ b/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -1,435 +1,498 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.serverless.v1.service.function.function_version.function_version_content import FunctionVersionContentList +from twilio.rest.serverless.v1.service.function.function_version.function_version_content import ( + FunctionVersionContentList, +) -class FunctionVersionList(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, function_sid): - """ - Initialize the FunctionVersionList +class FunctionVersionInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the Function Version resource is associated with - :param function_sid: The SID of the function that is the parent of the function version + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionList - """ - super(FunctionVersionList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'service_sid': service_sid, 'function_sid': function_sid, } - self._uri = '/Services/{service_sid}/Functions/{function_sid}/Versions'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionVersionContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "FunctionVersionContext": """ - 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. + 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: 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance] + def fetch(self) -> "FunctionVersionInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the FunctionVersionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched FunctionVersionInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the FunctionVersionInstance - :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.serverless.v1.service.function.function_version.FunctionVersionInstance] + :returns: The fetched FunctionVersionInstance """ - 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 function_version_content(self) -> FunctionVersionContentList: """ - Retrieve a single page of FunctionVersionInstance records from the API. - Request is executed immediately + Access the function_version_content + """ + return self._proxy.function_version_content - :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 FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage + :returns: Machine friendly representation """ - data = 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(method='GET', uri=self._uri, params=data, ) - return FunctionVersionPage(self._version, response, self._solution) +class FunctionVersionContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ - Retrieve a specific page of FunctionVersionInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the FunctionVersionContext - :returns: Page of FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 + ) ) - return FunctionVersionPage(self._version, response, self._solution) + self._function_version_content: Optional[FunctionVersionContentList] = None - def get(self, sid): + def fetch(self) -> FunctionVersionInstance: """ - Constructs a FunctionVersionContext + Fetch the FunctionVersionInstance - :param sid: The SID that identifies the Function Version resource to fetch - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + :returns: The fetched FunctionVersionInstance """ - return FunctionVersionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionVersionInstance( self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> FunctionVersionInstance: """ - Constructs a FunctionVersionContext + Asynchronous coroutine to fetch the FunctionVersionInstance - :param sid: The SID that identifies the Function Version resource to fetch - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + :returns: The fetched FunctionVersionInstance """ - return FunctionVersionContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionVersionInstance( self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=sid, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + @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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class FunctionVersionPage(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 FunctionVersionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Function Version resource is associated with - :param function_sid: The SID of the function that is the parent of the function version - - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionPage - """ - super(FunctionVersionPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: """ Build an instance of FunctionVersionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.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'], + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class FunctionVersionContext(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 FunctionVersionList(ListResource): - def __init__(self, version, service_sid, function_sid, sid): + def __init__(self, version: Version, service_sid: str, function_sid: str): """ - Initialize the FunctionVersionContext + Initialize the FunctionVersionList - :param Version 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 that identifies the Function Version resource to fetch + :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. - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext """ - super(FunctionVersionContext, self).__init__(version) + 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) - - # Dependents - self._function_version_content = None + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionVersionInstance]: """ - Fetch the 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. - :returns: The fetched FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return FunctionVersionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) + return self._version.stream(page, limits["limit"]) - @property - def function_version_content(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionVersionInstance]: """ - Access the function_version_content + 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: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList + :returns: Generator that will yield up to limit results """ - if self._function_version_content is None: - self._function_version_content = FunctionVersionContentList( - self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) - return self._function_version_content + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - def __repr__(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: """ - Provide a friendly representation + Lists FunctionVersionInstance 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 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. -class FunctionVersionInstance(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. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - class Visibility(object): - PUBLIC = "public" - PRIVATE = "private" - PROTECTED = "protected" + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - def __init__(self, version, payload, service_sid, function_sid, sid=None): + 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: """ - Initialize the FunctionVersionInstance + Retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately - :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance + :param page_token: PageToken provided by the API + :param page_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 """ - super(FunctionVersionInstance, self).__init__(version) + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'function_sid': payload.get('function_sid'), - 'path': payload.get('path'), - 'visibility': payload.get('visibility'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = { - 'service_sid': service_sid, - 'function_sid': function_sid, - '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 + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) - :returns: FunctionVersionContext for this FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext + async def 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: """ - 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 + Asynchronously retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The unique string that identifies the Function Version resource - :rtype: unicode - """ - return self._properties['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 SID of the Account that created the Function Version resource - :rtype: unicode + :returns: Page of FunctionVersionInstance """ - return self._properties['account_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def service_sid(self): - """ - :returns: The SID of the Service that the Function Version resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def function_sid(self): - """ - :returns: The SID of the function that is the parent of the function version - :rtype: unicode - """ - return self._properties['function_sid'] + headers["Accept"] = "application/json" - @property - def path(self): - """ - :returns: The URL-friendly string by which the function version can be referenced - :rtype: unicode - """ - return self._properties['path'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) - @property - def visibility(self): - """ - :returns: The access control that determines how the function version can be accessed - :rtype: FunctionVersionInstance.Visibility + def get_page(self, target_url: str) -> FunctionVersionPage: """ - return self._properties['visibility'] + Retrieve a specific page of FunctionVersionInstance records from the API. + Request is executed immediately - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Function Version resource was created - :rtype: datetime - """ - return self._properties['date_created'] + :param target_url: API-generated URL for the requested results page - @property - def url(self): - """ - :returns: The absolute URL of the Function Version resource - :rtype: unicode + :returns: Page of FunctionVersionInstance """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> FunctionVersionPage: """ - :returns: The links - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> FunctionVersionContext: """ - Fetch the FunctionVersionInstance + Constructs a FunctionVersionContext - :returns: The fetched FunctionVersionInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance + :param sid: The SID of the Function Version resource to fetch. """ - return self._proxy.fetch() + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=sid, + ) - @property - def function_version_content(self): + def __call__(self, sid: str) -> FunctionVersionContext: """ - Access the function_version_content + Constructs a FunctionVersionContext - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList + :param sid: The SID of the Function Version resource to fetch. """ - return self._proxy.function_version_content + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_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/serverless/v1/service/function/function_version/function_version_content.py b/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py index 95eb95cb6a..f16833da2a 100644 --- 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 @@ -1,288 +1,234 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page +from twilio.base.version import Version -class FunctionVersionContentList(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 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 - def __init__(self, version, service_sid, function_sid, sid): + @property + def _proxy(self) -> "FunctionVersionContentContext": """ - Initialize the FunctionVersionContentList + 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 SID of the Service that the Function Version resource is associated with - :param function_sid: The SID of the Function that is the parent of the Function Version - :param sid: The unique string that identifies the Function Version resource + :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 - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentList + def fetch(self) -> "FunctionVersionContentInstance": """ - super(FunctionVersionContentList, self).__init__(version) + Fetch the FunctionVersionContentInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'function_sid': function_sid, 'sid': sid, } - def get(self): + :returns: The fetched FunctionVersionContentInstance """ - Constructs a FunctionVersionContentContext + return self._proxy.fetch() - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext + async def fetch_async(self) -> "FunctionVersionContentInstance": """ - return FunctionVersionContentContext( - self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['sid'], - ) + Asynchronous coroutine to fetch the FunctionVersionContentInstance - def __call__(self): - """ - Constructs a FunctionVersionContentContext - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext + :returns: The fetched FunctionVersionContentInstance """ - return FunctionVersionContentContext( - self._version, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['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 FunctionVersionContentPage(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 FunctionVersionContentContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ - Initialize the FunctionVersionContentPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the Function Version resource is associated with - :param function_sid: The SID of the Function that is the parent of the Function Version - :param sid: The unique string that identifies the Function Version resource + Initialize the FunctionVersionContentContext - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentPage - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentPage + :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(FunctionVersionContentPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> FunctionVersionContentInstance: """ - Build an instance of FunctionVersionContentInstance + Fetch the FunctionVersionContentInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance + :returns: The fetched FunctionVersionContentInstance """ - return FunctionVersionContentInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - function_sid=self._solution['function_sid'], - sid=self._solution['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 FunctionVersionContentContext(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 FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, service_sid, function_sid, sid): + async def fetch_async(self) -> FunctionVersionContentInstance: """ - Initialize the FunctionVersionContentContext + Asynchronous coroutine to fetch the FunctionVersionContentInstance - :param Version 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 that identifies the Function Version content to fetch - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext + :returns: The fetched FunctionVersionContentInstance """ - super(FunctionVersionContentContext, self).__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) + headers = values.of({}) - def fetch(self): - """ - Fetch the FunctionVersionContentInstance + headers["Accept"] = "application/json" - :returns: The fetched FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_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) - - -class FunctionVersionContentInstance(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, function_sid, sid): """ - Initialize the FunctionVersionContentInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance - """ - super(FunctionVersionContentInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'function_sid': payload.get('function_sid'), - 'content': payload.get('content'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'function_sid': function_sid, 'sid': 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: FunctionVersionContentContext for this FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentContext - """ - 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 +class FunctionVersionContentList(ListResource): - @property - def sid(self): - """ - :returns: The unique string that identifies the Function Version resource - :rtype: unicode + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ - return self._properties['sid'] + Initialize the FunctionVersionContentList - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the Function Version resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def service_sid(self): - """ - :returns: The SID of the Service that the Function Version resource is associated with - :rtype: unicode """ - return self._properties['service_sid'] + super().__init__(version) - @property - def function_sid(self): - """ - :returns: The SID of the Function that is the parent of the Function Version - :rtype: unicode - """ - return self._properties['function_sid'] + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } - @property - def content(self): - """ - :returns: The content of the Function Version resource - :rtype: unicode + def get(self) -> FunctionVersionContentContext: """ - return self._properties['content'] + Constructs a FunctionVersionContentContext - @property - def url(self): """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + def __call__(self) -> FunctionVersionContentContext: """ - Fetch the FunctionVersionContentInstance + Constructs a FunctionVersionContentContext - :returns: The fetched FunctionVersionContentInstance - :rtype: twilio.rest.serverless.v1.service.function.function_version.function_version_content.FunctionVersionContentInstance """ - return self._proxy.fetch() + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_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) + 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 b54999d003..986e694221 100644 --- a/twilio/rest/studio/__init__.py +++ b/twilio/rest/studio/__init__.py @@ -1,72 +1,25 @@ -# coding=utf-8 -r""" -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.v2 import V2 +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 - self._v2 = 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 - - @property - def v2(self): - """ - :returns: Version v2 of studio - :rtype: twilio.rest.studio.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 - - @property - def flows(self): - """ - :rtype: twilio.rest.studio.v2.flow.FlowList - """ + def flows(self) -> FlowList: + warn( + "flows is deprecated. Use v2.flows instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.flows @property - def flow_validate(self): - """ - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateList - """ + def flow_validate(self) -> FlowValidateList: + warn( + "flow_validate is deprecated. Use v2.flow_validate instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v2.flow_validate - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/studio/v1/__init__.py b/twilio/rest/studio/v1/__init__.py index e1d0705da1..8ab7d71b6c 100644 --- a/twilio/rest/studio/v1/__init__.py +++ b/twilio/rest/studio/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 79c8dde100..533c1a45f5 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -1,427 +1,513 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - 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']) + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.delete_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 that identifies the resource to fetch - :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 that identifies the resource to fetch + 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: """ - return FlowContext(self._version, sid=sid, ) + Access the executions + """ + 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): - """ """ +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 - - def get_instance(self, payload): - """ - Build an instance of FlowInstance + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._engagements: Optional[EngagementList] = None + self._executions: Optional[ExecutionList] = None - :returns: twilio.rest.studio.v1.flow.FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance + def delete(self) -> bool: """ - return FlowInstance(self._version, payload, ) + Deletes the FlowInstance - 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 FlowContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the FlowContext + Asynchronous coroutine that deletes the FlowInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.studio.v1.flow.FlowContext - :rtype: twilio.rest.studio.v1.flow.FlowContext + :returns: True if delete succeeds, False otherwise """ - 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 - self._executions = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> FlowInstance: """ Fetch the FlowInstance + :returns: The fetched FlowInstance - :rtype: twilio.rest.studio.v1.flow.FlowInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def delete(self): + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowInstance: """ - Deletes the FlowInstance + Asynchronous coroutine to fetch the FlowInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched FlowInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) @property - def engagements(self): + 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 @property - def executions(self): + def executions(self) -> ExecutionList: """ Access the executions - - :returns: twilio.rest.studio.v1.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList """ if self._executions is None: - self._executions = ExecutionList(self._version, flow_sid=self._solution['sid'], ) + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) return self._executions - 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 FlowInstance(InstanceResource): - """ """ +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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'status': payload.get('status'), - 'version': deserialize.integer(payload.get('version')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource - @property - def account_sid(self): """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + super().__init__(version) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the Flow - :rtype: unicode - """ - return self._properties['friendly_name'] + self._uri = "/Flows" - @property - def status(self): - """ - :returns: The status of the Flow - :rtype: FlowInstance.Status + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: """ - return self._properties['status'] + 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 latest version number of the Flow's definition - :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[FlowInstance]: """ - return self._properties['version'] + 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 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 ISO 8601 date and time in GMT when the resource 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[FlowInstance]: """ - return self._properties['date_created'] + 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 """ - :returns: The ISO 8601 date and time in GMT when the resource 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[FlowInstance]: """ - return self._properties['date_updated'] + 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 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, + ) -> FlowPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 = 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: Nested resource URLs - :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['links'] + 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 FlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlowPage: """ - Fetch the FlowInstance + Retrieve a specific page of FlowInstance records from the API. + Request is executed immediately - :returns: The 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 = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) - def delete(self): + async def get_page_async(self, target_url: str) -> FlowPage: """ - Deletes the FlowInstance + Asynchronously retrieve a specific page of FlowInstance 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 FlowInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) - @property - def engagements(self): + def get(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) - @property - def executions(self): + def __call__(self, sid: str) -> FlowContext: """ - Access the executions + Constructs a FlowContext - :returns: twilio.rest.studio.v1.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList + :param sid: The SID of the Flow resource to fetch. """ - return self._proxy.executions + 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 5f57ebbca0..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, flow_sid): - """ - Initialize the EngagementList +class EngagementInstance(InstanceResource): - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow + 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']) + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return EngagementPage(self._version, response, self._solution) + return await self._proxy.delete_async() - 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 the EngagementInstance + Asynchronous coroutine to fetch the EngagementInstance - :param unicode to: The Contact phone number to start a Studio Flow Engagement - :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement - :param dict parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow - :returns: The 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), }) + return await self._proxy.fetch_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) - - def get(self, sid): + @property + def engagement_context(self) -> EngagementContextList: """ - Constructs a EngagementContext - - :param sid: The SID of the Engagement resource to fetch - - :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 of the Engagement resource to fetch - - :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): - """ """ +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 SID of the Flow + 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 - - def get_instance(self, payload): - """ - Build an instance of EngagementInstance + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._engagement_context: Optional[EngagementContextList] = None + self._steps: Optional[StepList] = None - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + def delete(self) -> bool: """ - return EngagementInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the EngagementInstance - 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 EngagementContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, flow_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the EngagementContext + Asynchronous coroutine that deletes the EngagementInstance - :param Version version: Version that contains the resource - :param flow_sid: Flow SID - :param sid: The SID of the Engagement resource to fetch - :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext + :returns: True if delete succeeds, False otherwise """ - 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({}) - # Dependents - self._steps = None - self._engagement_context = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> EngagementInstance: """ Fetch the EngagementInstance + :returns: The fetched EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) return EngagementInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> EngagementInstance: """ - Deletes the EngagementInstance + Asynchronous coroutine to fetch the EngagementInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) - @property - def steps(self): + :returns: The fetched EngagementInstance """ - Access the steps - :returns: twilio.rest.studio.v1.flow.engagement.step.StepList - :rtype: twilio.rest.studio.v1.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 + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) @property - def engagement_context(self): + def engagement_context(self) -> EngagementContextList: """ Access the engagement_context - - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList """ 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._engagement_context - def __repr__(self): + @property + def steps(self) -> StepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = StepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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): - """ """ +class EngagementPage(Page): - class Status(object): - ACTIVE = "active" - ENDED = "ended" + def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: + """ + Build an instance of EngagementInstance + + :param payload: Payload response from the API + """ + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) - def __init__(self, version, payload, flow_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the EngagementInstance + Provide a friendly representation - :returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :returns: Machine friendly representation """ - super(EngagementInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'contact_sid': payload.get('contact_sid'), - 'contact_channel_address': payload.get('contact_channel_address'), - 'context': payload.get('context'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } +class EngagementList(ListResource): - @property - def _proxy(self): + def __init__(self, version: Version, flow_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 EngagementList - :returns: EngagementContext for this EngagementInstance - :rtype: twilio.rest.studio.v1.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 + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow to read Engagements from. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: """ - return self._properties['flow_sid'] + Create the EngagementInstance - @property - def contact_sid(self): - """ - :returns: The SID of the Contact - :rtype: unicode + :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 = 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 phone number, SIP address or Client identifier that triggered this Engagement - :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_channel_address'] - @property - def context(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 current state of the execution flow - :rtype: dict + 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 = self.page(page_size=limits["page_size"]) - @property - def status(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 status of the Engagement - :rtype: EngagementInstance.Status + 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['status'] + 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[EngagementInstance]: """ - :returns: The ISO 8601 date and time in GMT when the Engagement was created - :rtype: datetime + 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 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[EngagementInstance]: """ - :returns: The ISO 8601 date and time in GMT when the Engagement was last updated - :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_updated'] + 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, + ) -> EngagementPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 = 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 URLs of the Engagement's nested resources - :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['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" - def fetch(self): + 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: """ - Fetch the EngagementInstance + Retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately - :returns: The fetched EngagementInstance - :rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return EngagementPage(self._version, response, self._solution) - def delete(self): + async def get_page_async(self, target_url: str) -> EngagementPage: """ - Deletes the EngagementInstance + Asynchronously retrieve a specific page of EngagementInstance 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 EngagementInstance """ - return self._proxy.delete() + 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 e5f7c16c02..73161011eb 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -1,263 +1,219 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +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: Flow SID - :param engagement_sid: 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): - """ """ +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: Flow SID - :param engagement_sid: 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 """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return EngagementContextInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], + 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 + async def fetch_async(self) -> EngagementContextInstance: """ - return '' - + Asynchronous coroutine to fetch the EngagementContextInstance -class EngagementContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, engagement_sid): + :returns: The fetched EngagementContextInstance """ - Initialize the EngagementContextContext - :param Version version: Version that contains the resource - :param flow_sid: Flow SID - :param engagement_sid: Engagement SID + headers = values.of({}) - :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext - """ - 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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the EngagementContextInstance - - :returns: The fetched EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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) - + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class EngagementContextInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, flow_sid, engagement_sid): - """ - Initialize the EngagementContextInstance - - :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.get('account_sid'), - 'context': payload.get('context'), - 'engagement_sid': payload.get('engagement_sid'), - 'flow_sid': payload.get('flow_sid'), - 'url': payload.get('url'), - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_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 EngagementContextList(ListResource): - :returns: EngagementContextContext for this EngagementContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ - 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 + Initialize the EngagementContextList - @property - def account_sid(self): - """ - :returns: Account SID - :rtype: unicode - """ - return self._properties['account_sid'] + :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 context(self): """ - :returns: Flow state - :rtype: dict - """ - return self._properties['context'] + super().__init__(version) - @property - def engagement_sid(self): - """ - :returns: 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: Flow SID - :rtype: unicode + def get(self) -> EngagementContextContext: """ - return self._properties['flow_sid'] + Constructs a EngagementContextContext - @property - def url(self): - """ - :returns: The URL of the resource - :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 the EngagementContextInstance + Constructs a EngagementContextContext - :returns: The 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 8543dde406..a5017c3313 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -1,449 +1,496 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - 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 SID of the Flow - :param engagement_sid: The SID of the Engagement + 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) - - # Path Solution - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, } - self._uri = '/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps'.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: StepContext for this 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 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 = StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.engagement.step.StepInstance] + def fetch(self) -> "StepInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the StepInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched StepInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the StepInstance - :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.step.StepInstance] + :returns: The fetched StepInstance """ - 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 step_context(self) -> StepContextList: """ - Retrieve a single page of StepInstance records from the API. - Request is executed immediately + Access the step_context + """ + return self._proxy.step_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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage + :returns: Machine friendly representation """ - data = 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(method='GET', uri=self._uri, params=data, ) - return StepPage(self._version, response, self._solution) +class StepContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): """ - 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 + Initialize the StepContext - :returns: Page of StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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(self, sid): + def fetch(self) -> StepInstance: """ - Constructs a StepContext + Fetch the StepInstance - :param sid: The SID that identifies the resource to fetch - :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 = self._version.fetch(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 __call__(self, sid): + async def fetch_async(self) -> StepInstance: """ - Constructs a StepContext + Asynchronous coroutine to fetch the StepInstance - :param sid: The SID that identifies the resource to fetch - :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): - """ """ - - 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 SID of the Flow - :param engagement_sid: The SID of the Engagement - :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): - """ """ +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 SID of the Flow - :param engagement_sid: The SID of the Engagement - :param sid: The SID that identifies the resource to fetch + :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 the 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. - :returns: The fetched StepInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return StepInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - sid=self._solution['sid'], - ) + return self._version.stream(page, limits["limit"]) - @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): - """ """ - - 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.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'engagement_sid': payload.get('engagement_sid'), - 'name': payload.get('name'), - 'context': payload.get('context'), - 'transitioned_from': payload.get('transitioned_from'), - 'transitioned_to': payload.get('transitioned_to'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 SID of the Account that created the resource - :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 SID of the Flow - :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 SID of the Engagement - :rtype: unicode - """ - return self._properties['engagement_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The event that caused the Flow to transition to the Step - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def context(self): - """ - :returns: The current state of the flow - :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 Widget that preceded the Widget for the Step - :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 Widget that will follow the Widget for the Step - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 absolute URL of the resource - :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 URLs of related resources - :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 the StepInstance + Constructs a StepContext - :returns: The 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 5407f0ab63..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,280 +1,236 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +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 SID of the Flow - :param engagement_sid: The SID of the Engagement - :param step_sid: 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): - """ """ +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 SID of the Flow - :param engagement_sid: The SID of the Engagement - :param step_sid: 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 """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return StepContextInstance( self._version, payload, - flow_sid=self._solution['flow_sid'], - engagement_sid=self._solution['engagement_sid'], - step_sid=self._solution['step_sid'], + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], ) - def __repr__(self): + async def fetch_async(self) -> StepContextInstance: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the StepContextInstance -class StepContextContext(InstanceContext): - """ """ - - def __init__(self, version, flow_sid, engagement_sid, step_sid): + :returns: The fetched StepContextInstance """ - Initialize the StepContextContext - - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param engagement_sid: The SID of the Engagement - :param step_sid: Step SID - :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext - """ - super(StepContextContext, self).__init__(version) + headers = values.of({}) - # 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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the StepContextInstance - - :returns: The fetched StepContextInstance - :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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): - """ """ - - def __init__(self, version, payload, flow_sid, engagement_sid, step_sid): - """ - Initialize the StepContextInstance - - :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.get('account_sid'), - 'context': payload.get('context'), - 'engagement_sid': payload.get('engagement_sid'), - 'flow_sid': payload.get('flow_sid'), - 'step_sid': payload.get('step_sid'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'engagement_sid': engagement_sid, 'step_sid': step_sid, } + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @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: 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 +class StepContextList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): """ - return self._properties['account_sid'] + Initialize the StepContextList - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['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 engagement_sid(self): - """ - :returns: The SID of the Engagement - :rtype: unicode """ - return self._properties['engagement_sid'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :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: Step SID - :rtype: unicode + def get(self) -> StepContextContext: """ - return self._properties['step_sid'] + Constructs a StepContextContext - @property - def url(self): """ - :returns: The absolute URL of the resource - :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 the StepContextInstance + Constructs a StepContextContext - :returns: The 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 index 22fbf223fe..624b381768 100644 --- a/twilio/rest/studio/v1/flow/execution/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -1,538 +1,740 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.execution.execution_context import ExecutionContextList from twilio.rest.studio.v1.flow.execution.execution_step import ExecutionStepList -class ExecutionList(ListResource): - """ """ - - def __init__(self, version, flow_sid): - """ - Initialize the ExecutionList +class ExecutionInstance(InstanceResource): - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow + class Status(object): + ACTIVE = "active" + ENDED = "ended" - :returns: twilio.rest.studio.v1.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList - """ - super(ExecutionList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Executions'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None - def stream(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + @property + def _proxy(self) -> "ExecutionContext": """ - 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 Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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) + 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.execution.ExecutionInstance] + :returns: ExecutionContext for this ExecutionInstance """ - 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']) + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + def delete(self) -> bool: """ - Lists ExecutionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ExecutionInstance - :param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.execution.ExecutionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - date_created_from=date_created_from, - date_created_to=date_created_to, - limit=limit, - page_size=page_size, - )) + return self._proxy.delete() - def page(self, date_created_from=values.unset, date_created_to=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 ExecutionInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ExecutionInstance - :param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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 - :returns: Page of ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage + :returns: True if delete succeeds, False otherwise """ - 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, - }) + return await self._proxy.delete_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance - return ExecutionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ExecutionInstance """ - Retrieve a specific page of ExecutionInstance 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 ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage + async def fetch_async(self) -> "ExecutionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the ExecutionInstance - return ExecutionPage(self._version, response, self._solution) - def create(self, to, from_, parameters=values.unset): + :returns: The fetched ExecutionInstance """ - Create the ExecutionInstance - - :param unicode to: The Contact phone number to start a Studio Flow Execution - :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Execution - :param dict parameters: JSON data that will be added to the Flow's context + return await self._proxy.fetch_async() - :returns: The created ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) + Update the ExecutionInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param status: - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) - def get(self, sid): + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": """ - Constructs a ExecutionContext + Asynchronous coroutine to update the ExecutionInstance - :param sid: The SID of the Execution resource to fetch + :param status: - :returns: twilio.rest.studio.v1.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext + :returns: The updated ExecutionInstance """ - return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return await self._proxy.update_async( + status=status, + ) - def __call__(self, sid): + @property + def execution_context(self) -> ExecutionContextList: """ - Constructs a ExecutionContext - - :param sid: The SID of the Execution resource to fetch + Access the execution_context + """ + return self._proxy.execution_context - :returns: twilio.rest.studio.v1.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps """ - return ExecutionContext(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 ExecutionPage(Page): - """ """ +class ExecutionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, sid: str): """ - Initialize the ExecutionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow + Initialize the ExecutionContext - :returns: twilio.rest.studio.v1.flow.execution.ExecutionPage - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionPage + :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(ExecutionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExecutionInstance + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None - :returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + def delete(self) -> bool: """ - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the ExecutionInstance - 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 ExecutionContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, flow_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the ExecutionContext + Asynchronous coroutine that deletes the ExecutionInstance - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param sid: The SID of the Execution resource to fetch - :returns: twilio.rest.studio.v1.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext + :returns: True if delete succeeds, False otherwise """ - super(ExecutionContext, self).__init__(version) - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Executions/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._steps = None - self._execution_context = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ExecutionInstance: """ Fetch the ExecutionInstance + :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> ExecutionInstance: """ - Deletes the ExecutionInstance + Asynchronous coroutine to fetch the ExecutionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ExecutionInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, status): + 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 ExecutionInstance.Status status: The status of the Execution + :param status: :returns: The updated ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - @property - def steps(self): + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: """ - Access the steps + Asynchronous coroutine to update the ExecutionInstance - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList + :param status: + + :returns: The updated ExecutionInstance """ - if self._steps is None: - self._steps = ExecutionStepList( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['sid'], - ) - return self._steps + + 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): + def execution_context(self) -> ExecutionContextList: """ Access the execution_context - - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList """ if self._execution_context is None: self._execution_context = ExecutionContextList( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['sid'], + self._solution["flow_sid"], + self._solution["sid"], ) return self._execution_context - def __repr__(self): + @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 - :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 ExecutionInstance(InstanceResource): - """ """ +class ExecutionPage(Page): - class Status(object): - ACTIVE = "active" - ENDED = "ended" + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance - def __init__(self, version, payload, flow_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the ExecutionInstance + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) - :returns: twilio.rest.studio.v1.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + def __repr__(self) -> str: """ - super(ExecutionInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'contact_sid': payload.get('contact_sid'), - 'contact_channel_address': payload.get('contact_channel_address'), - 'context': payload.get('context'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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 ExecutionList(ListResource): - :returns: ExecutionContext for this ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext + def __init__(self, version: Version, flow_sid: str): """ - if self._context is None: - self._context = ExecutionContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the ExecutionList - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. - @property - def account_sid(self): """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - @property - def contact_sid(self): + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - :returns: The SID of the Contact - :rtype: unicode - """ - return self._properties['contact_sid'] + Create the ExecutionInstance - @property - def contact_channel_address(self): - """ - :returns: The phone number, SIP address or Client identifier that triggered the Execution - :rtype: unicode - """ - return self._properties['contact_channel_address'] + :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. - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict + :returns: The created ExecutionInstance """ - return self._properties['context'] - @property - def status(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 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: """ - :returns: The status of the Execution - :rtype: ExecutionInstance.Status + 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 """ - return self._properties['status'] - @property - def date_created(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 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + 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"], + ) - @property - def date_updated(self): + 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :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: """ - :returns: Nested resource URLs - :rtype: unicode + 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 """ - return self._properties['links'] + 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"}) - def fetch(self): + 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: """ - Fetch the ExecutionInstance + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately - :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + :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 """ - return self._proxy.fetch() + 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"}) - def delete(self): + 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: """ - Deletes the ExecutionInstance + Retrieve a specific page of ExecutionInstance 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 ExecutionInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) - def update(self, status): + async def get_page_async(self, target_url: str) -> ExecutionPage: """ - Update the ExecutionInstance + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately - :param ExecutionInstance.Status status: The status of the Execution + :param target_url: API-generated URL for the requested results page - :returns: The updated ExecutionInstance - :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance + :returns: Page of ExecutionInstance """ - return self._proxy.update(status, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) - @property - def steps(self): + def get(self, sid: str) -> ExecutionContext: """ - Access the steps + Constructs a ExecutionContext - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList + :param sid: The SID of the Execution resource to update. """ - return self._proxy.steps + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - @property - def execution_context(self): + def __call__(self, sid: str) -> ExecutionContext: """ - Access the execution_context + Constructs a ExecutionContext - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList + :param sid: The SID of the Execution resource to update. """ - return self._proxy.execution_context + return ExecutionContext( + 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/execution/execution_context.py b/twilio/rest/studio/v1/flow/execution/execution_context.py index b06b70b8dc..0841a9ef24 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -1,263 +1,219 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 ExecutionContextList(ListResource): - """ """ +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 - def __init__(self, version, flow_sid, execution_sid): + @property + def _proxy(self) -> "ExecutionContextContext": """ - Initialize the ExecutionContextList + 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 SID of the Flow - :param execution_sid: The SID of the Execution + :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 - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList + def fetch(self) -> "ExecutionContextInstance": """ - super(ExecutionContextList, self).__init__(version) + Fetch the ExecutionContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } - def get(self): + :returns: The fetched ExecutionContextInstance """ - Constructs a ExecutionContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + async def fetch_async(self) -> "ExecutionContextInstance": """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + Asynchronous coroutine to fetch the ExecutionContextInstance - def __call__(self): - """ - Constructs a ExecutionContextContext - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + :returns: The fetched ExecutionContextInstance """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 ExecutionContextPage(Page): - """ """ +class ExecutionContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - Initialize the ExecutionContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + Initialize the ExecutionContextContext - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextPage - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextPage + :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(ExecutionContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) - def get_instance(self, payload): + def fetch(self) -> ExecutionContextInstance: """ - Build an instance of ExecutionContextInstance + Fetch the ExecutionContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> ExecutionContextInstance: """ - return '' - + Asynchronous coroutine to fetch the ExecutionContextInstance -class ExecutionContextContext(InstanceContext): - """ """ - def __init__(self, version, flow_sid, execution_sid): + :returns: The fetched ExecutionContextInstance """ - Initialize the ExecutionContextContext - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + headers = values.of({}) - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext - """ - super(ExecutionContextContext, self).__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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the ExecutionContextInstance - - :returns: The fetched ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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 ExecutionContextInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, flow_sid, execution_sid): - """ - Initialize the ExecutionContextInstance - - :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance - """ - super(ExecutionContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'context': payload.get('context'), - 'flow_sid': payload.get('flow_sid'), - 'execution_sid': payload.get('execution_sid'), - 'url': payload.get('url'), - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_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 ExecutionContextList(ListResource): - :returns: ExecutionContextContext for this ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - 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 + Initialize the ExecutionContextList - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def context(self): """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode + def get(self) -> ExecutionContextContext: """ - return self._properties['execution_sid'] + Constructs a ExecutionContextContext - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode """ - return self._properties['url'] + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - def fetch(self): + def __call__(self) -> ExecutionContextContext: """ - Fetch the ExecutionContextInstance + Constructs a ExecutionContextContext - :returns: The fetched ExecutionContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextInstance """ - return self._proxy.fetch() + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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/execution_step/__init__.py b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py index 96a13df703..50a1e2371d 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -1,449 +1,498 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.execution.execution_step.execution_step_context import ExecutionStepContextList +from twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) -class ExecutionStepList(ListResource): - """ """ - - def __init__(self, version, flow_sid, execution_sid): - """ - Initialize the ExecutionStepList +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") - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList + @property + def _proxy(self) -> "ExecutionStepContext": """ - super(ExecutionStepList, self).__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) + 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: ExecutionStepContext for this 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 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 = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance] + def fetch(self) -> "ExecutionStepInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ExecutionStepInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ExecutionStepInstance - :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.execution.execution_step.ExecutionStepInstance] + :returns: The fetched ExecutionStepInstance """ - 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 step_context(self) -> ExecutionStepContextList: """ - Retrieve a single page of ExecutionStepInstance records from the API. - Request is executed immediately + Access the step_context + """ + return self._proxy.step_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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage + :returns: Machine friendly representation """ - data = 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(method='GET', uri=self._uri, params=data, ) - return ExecutionStepPage(self._version, response, self._solution) +class ExecutionStepContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ - Retrieve a specific page of ExecutionStepInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the ExecutionStepContext - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return ExecutionStepPage(self._version, response, self._solution) + self._step_context: Optional[ExecutionStepContextList] = None - def get(self, sid): + def fetch(self) -> ExecutionStepInstance: """ - Constructs a ExecutionStepContext + Fetch the ExecutionStepInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext + :returns: The fetched ExecutionStepInstance """ - return ExecutionStepContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> ExecutionStepInstance: """ - Constructs a ExecutionStepContext + Asynchronous coroutine to fetch the ExecutionStepInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext + :returns: The fetched ExecutionStepInstance """ - return ExecutionStepContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + @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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class ExecutionStepPage(Page): - """ """ - - def __init__(self, version, response, solution): - """ - Initialize the ExecutionStepPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage - """ - super(ExecutionStepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: """ Build an instance of ExecutionStepInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ExecutionStepContext(InstanceContext): - """ """ +class ExecutionStepList(ListResource): - def __init__(self, version, flow_sid, execution_sid, sid): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - Initialize the ExecutionStepContext + Initialize the ExecutionStepList - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param sid: The unique string that identifies the resource + :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. - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext """ - super(ExecutionStepContext, self).__init__(version) + 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) - - # Dependents - self._step_context = None + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: """ - Fetch the 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. - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return ExecutionStepInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=self._solution['sid'], - ) + return self._version.stream(page, limits["limit"]) - @property - def step_context(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: """ - Access the step_context + 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. - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - """ - if self._step_context is None: - self._step_context = ExecutionStepContextList( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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[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. -class ExecutionStepInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, flow_sid, execution_sid, sid=None): - """ - Initialize the ExecutionStepInstance - - :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance - """ - super(ExecutionStepInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'execution_sid': payload.get('execution_sid'), - 'name': payload.get('name'), - 'context': payload.get('context'), - 'transitioned_from': payload.get('transitioned_from'), - 'transitioned_to': payload.get('transitioned_to'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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, - 'execution_sid': execution_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[ExecutionStepInstance]: """ - 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 ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: ExecutionStepContext for this ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 unique string that identifies the resource - :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, + ) -> ExecutionStepPage: """ - return self._properties['sid'] + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 SID of the Flow - :rtype: unicode + :returns: Page of ExecutionStepInstance """ - return self._properties['flow_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode - """ - return self._properties['execution_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The event that caused the Flow to transition to the Step - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(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, + ) -> ExecutionStepPage: """ - :returns: The Widget that preceded the Widget for the Step - :rtype: unicode - """ - return self._properties['transitioned_from'] + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately - @property - def transitioned_to(self): - """ - :returns: The Widget that will follow the Widget for the Step - :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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + :returns: Page of ExecutionStepInstance """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ - :returns: The URLs of related resources - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ExecutionStepContext: """ - Fetch the ExecutionStepInstance + Constructs a ExecutionStepContext - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance + :param sid: The SID of the ExecutionStep resource to fetch. """ - return self._proxy.fetch() + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - @property - def step_context(self): + def __call__(self, sid: str) -> ExecutionStepContext: """ - Access the step_context + Constructs a ExecutionStepContext - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList + :param sid: The SID of the ExecutionStep resource to fetch. """ - return self._proxy.step_context + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py index 02c2658924..78249a9562 100644 --- 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 @@ -1,280 +1,236 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 ExecutionStepContextList(ListResource): - """ """ +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 - def __init__(self, version, flow_sid, execution_sid, step_sid): + @property + def _proxy(self) -> "ExecutionStepContextContext": """ - Initialize the ExecutionStepContextList + 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 SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID + :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 - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList + def fetch(self) -> "ExecutionStepContextInstance": """ - super(ExecutionStepContextList, self).__init__(version) + Fetch the ExecutionStepContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } - def get(self): + :returns: The fetched ExecutionStepContextInstance """ - Constructs a ExecutionStepContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + async def fetch_async(self) -> "ExecutionStepContextInstance": """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + Asynchronous coroutine to fetch the ExecutionStepContextInstance - def __call__(self): - """ - Constructs a ExecutionStepContextContext - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + :returns: The fetched ExecutionStepContextInstance """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 ExecutionStepContextPage(Page): - """ """ +class ExecutionStepContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - Initialize the ExecutionStepContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID + Initialize the ExecutionStepContextContext - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextPage - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextPage + :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(ExecutionStepContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ExecutionStepContextInstance: """ - Build an instance of ExecutionStepContextInstance + Fetch the ExecutionStepContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - def __repr__(self): + async def fetch_async(self) -> ExecutionStepContextInstance: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the ExecutionStepContextInstance -class ExecutionStepContextContext(InstanceContext): - """ """ - - def __init__(self, version, flow_sid, execution_sid, step_sid): + :returns: The fetched ExecutionStepContextInstance """ - Initialize the ExecutionStepContextContext - - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - """ - super(ExecutionStepContextContext, self).__init__(version) + headers = values.of({}) - # 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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the ExecutionStepContextInstance - - :returns: The fetched ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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 ExecutionStepContextInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, flow_sid, execution_sid, step_sid): - """ - Initialize the ExecutionStepContextInstance - - :returns: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - """ - super(ExecutionStepContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'context': payload.get('context'), - 'execution_sid': payload.get('execution_sid'), - 'flow_sid': payload.get('flow_sid'), - 'step_sid': payload.get('step_sid'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @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: ExecutionStepContextContext for this ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - """ - 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 +class ExecutionStepContextList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - return self._properties['account_sid'] + Initialize the ExecutionStepContextList - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + :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. - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode """ - return self._properties['execution_sid'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } - @property - def step_sid(self): - """ - :returns: Step SID - :rtype: unicode + def get(self) -> ExecutionStepContextContext: """ - return self._properties['step_sid'] + Constructs a ExecutionStepContextContext - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) - def fetch(self): + def __call__(self) -> ExecutionStepContextContext: """ - Fetch the ExecutionStepContextInstance + Constructs a ExecutionStepContextContext - :returns: The fetched ExecutionStepContextInstance - :rtype: twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance """ - return self._proxy.fetch() + 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): + 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/v2/__init__.py b/twilio/rest/studio/v2/__init__.py index 5818742739..83ccc8e0a9 100644 --- a/twilio/rest/studio/v2/__init__.py +++ b/twilio/rest/studio/v2/__init__.py @@ -1,53 +1,51 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Studio - :returns: V2 version of Studio - :rtype: twilio.rest.studio.v2.V2.V2 + :param domain: The Twilio.studio domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._flows = None - self._flow_validate = None + super().__init__(domain, "v2") + self._flows: Optional[FlowList] = None + self._flow_validate: Optional[FlowValidateList] = None @property - def flows(self): - """ - :rtype: twilio.rest.studio.v2.flow.FlowList - """ + def flows(self) -> FlowList: if self._flows is None: self._flows = FlowList(self) return self._flows @property - def flow_validate(self): - """ - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateList - """ + def flow_validate(self) -> FlowValidateList: if self._flow_validate is None: self._flow_validate = FlowValidateList(self) return self._flow_validate - 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/v2/flow/__init__.py b/twilio/rest/studio/v2/flow/__init__.py index 1f1de674e3..b4c542fdc0 100644 --- a/twilio/rest/studio/v2/flow/__init__.py +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -1,578 +1,746 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.v2.flow.execution import ExecutionList from twilio.rest.studio.v2.flow.flow_revision import FlowRevisionList -from twilio.rest.studio.v2.flow.test_user import FlowTestUserList +from twilio.rest.studio.v2.flow.flow_test_user import FlowTestUserList -class FlowList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the FlowList + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" - :param Version version: Version that contains the resource + """ + :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") - :returns: twilio.rest.studio.v2.flow.FlowList - :rtype: twilio.rest.studio.v2.flow.FlowList + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": """ - super(FlowList, 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 = '/Flows'.format(**self._solution) + :returns: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, friendly_name, status, definition, - commit_message=values.unset): + def delete(self) -> bool: """ - Create the FlowInstance + Deletes the FlowInstance - :param unicode friendly_name: The string that you assigned to describe the Flow - :param FlowInstance.Status status: The status of the Flow - :param dict definition: JSON representation of flow definition - :param unicode commit_message: Description on change made in the revision - :returns: The created FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Status': status, - 'Definition': serialize.object(definition), - 'CommitMessage': commit_message, - }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance - return FlowInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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) + return await self._proxy.delete_async() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v2.flow.FlowInstance] + def fetch(self) -> "FlowInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the FlowInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched FlowInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch 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.v2.flow.FlowInstance] + :returns: The fetched FlowInstance """ - 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, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> "FlowInstance": """ - Retrieve a single page of FlowInstance records from the API. - Request is executed immediately + Update 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 + :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: Page of FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowPage + :returns: The updated FlowInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return FlowPage(self._version, response, self._solution) + return self._proxy.update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + ) - def get_page(self, target_url): + 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": """ - Retrieve a specific page of FlowInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the FlowInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowPage + :returns: The updated FlowInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, ) - return FlowPage(self._version, response, self._solution) + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions - def get(self, sid): + @property + def revisions(self) -> FlowRevisionList: """ - Constructs a FlowContext + Access the revisions + """ + return self._proxy.revisions - :param sid: The SID that identifies the resource to fetch + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + return self._proxy.test_users - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.flow.FlowContext + def __repr__(self) -> str: """ - return FlowContext(self._version, sid=sid, ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a FlowContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.flow.FlowContext - """ - return FlowContext(self._version, sid=sid, ) +class FlowContext(InstanceContext): - def __repr__(self): + def __init__(self, version: Version, sid: str): """ - Provide a friendly representation + Initialize the FlowContext - :returns: Machine friendly representation - :rtype: str + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. """ - return '' + super().__init__(version) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) -class FlowPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + self._executions: Optional[ExecutionList] = None + self._revisions: Optional[FlowRevisionList] = None + self._test_users: Optional[FlowTestUserList] = None - def __init__(self, version, response, solution): + def delete(self) -> bool: """ - Initialize the FlowPage + Deletes the FlowInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.studio.v2.flow.FlowPage - :rtype: twilio.rest.studio.v2.flow.FlowPage + :returns: True if delete succeeds, False otherwise """ - super(FlowPage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def get_instance(self, payload): + async def delete_async(self) -> bool: """ - Build an instance of FlowInstance + Asynchronous coroutine that deletes the FlowInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v2.flow.FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + :returns: True if delete succeeds, False otherwise """ - return FlowInstance(self._version, payload, ) - def __repr__(self): + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: """ - Provide a friendly representation + Fetch the FlowInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched FlowInstance """ - return '' + headers = values.of({}) -class FlowContext(InstanceContext): - """ 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 FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> FlowInstance: """ - Initialize the FlowContext + Asynchronous coroutine to fetch the FlowInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.studio.v2.flow.FlowContext - :rtype: twilio.rest.studio.v2.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._revisions = None - self._test_users = None - self._executions = None + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def update(self, status, friendly_name=values.unset, definition=values.unset, - commit_message=values.unset): + 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 FlowInstance.Status status: The status of the Flow - :param unicode friendly_name: The string that you assigned to describe the Flow - :param dict definition: JSON representation of flow definition - :param unicode commit_message: Description on change made in the revision + :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 - :rtype: twilio.rest.studio.v2.flow.FlowInstance """ - data = values.of({ - 'Status': status, - 'FriendlyName': friendly_name, - 'Definition': serialize.object(definition), - 'CommitMessage': commit_message, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({}) - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): - """ - Fetch the FlowInstance + headers["Accept"] = "application/json" - :returns: The fetched FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + 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: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Asynchronous coroutine to update the FlowInstance - return FlowInstance(self._version, payload, sid=self._solution['sid'], ) + :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. - def delete(self): + :returns: The updated FlowInstance """ - Deletes the FlowInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions @property - def revisions(self): + def revisions(self) -> FlowRevisionList: """ Access the revisions - - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList """ if self._revisions is None: - self._revisions = FlowRevisionList(self._version, sid=self._solution['sid'], ) + self._revisions = FlowRevisionList( + self._version, + self._solution["sid"], + ) return self._revisions @property - def test_users(self): + def test_users(self) -> FlowTestUserList: """ Access the test_users - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserList - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserList """ if self._test_users is None: - self._test_users = FlowTestUserList(self._version, sid=self._solution['sid'], ) + self._test_users = FlowTestUserList( + self._version, + self._solution["sid"], + ) return self._test_users - @property - def executions(self): + def __repr__(self) -> str: """ - Access the executions + 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): - :returns: twilio.rest.studio.v2.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionList + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: """ - if self._executions is None: - self._executions = ExecutionList(self._version, flow_sid=self._solution['sid'], ) - return self._executions + Build an instance of FlowInstance + + :param payload: Payload response from the API + """ + return FlowInstance(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 FlowInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" +class FlowList(ListResource): - def __init__(self, version, payload, sid=None): - """ - Initialize the FlowInstance - - :returns: twilio.rest.studio.v2.flow.FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance - """ - super(FlowInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'definition': payload.get('definition'), - 'status': payload.get('status'), - 'revision': deserialize.integer(payload.get('revision')), - 'commit_message': payload.get('commit_message'), - 'valid': payload.get('valid'), - 'errors': payload.get('errors'), - 'warnings': payload.get('warnings'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'webhook_url': payload.get('webhook_url'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + def __init__(self, version: Version): + """ + Initialize the FlowList - # 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: FlowContext for this FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowContext - """ - if self._context is None: - self._context = FlowContext(self._version, sid=self._solution['sid'], ) - return self._context + self._uri = "/Flows" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def create( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: """ - return self._properties['sid'] + Create the FlowInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the Flow - :rtype: unicode + :returns: The created FlowInstance """ - return self._properties['friendly_name'] - @property - def definition(self): - """ - :returns: JSON representation of flow definition - :rtype: dict - """ - return self._properties['definition'] + 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"}) - @property - def status(self): - """ - :returns: The status of the Flow - :rtype: FlowInstance.Status - """ - return self._properties['status'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def revision(self): - """ - :returns: The latest revision number of the Flow's definition - :rtype: unicode - """ - return self._properties['revision'] + headers["Accept"] = "application/json" - @property - def commit_message(self): - """ - :returns: Description on change made in the revision - :rtype: unicode - """ - return self._properties['commit_message'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def valid(self): - """ - :returns: Boolean if the flow definition is valid - :rtype: bool - """ - return self._properties['valid'] + return FlowInstance(self._version, payload) - @property - def errors(self): + async def create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: """ - :returns: List of error in the flow definition - :rtype: dict - """ - return self._properties['errors'] + Asynchronously create the FlowInstance - @property - def warnings(self): - """ - :returns: List of warnings in the flow definition - :rtype: dict - """ - return self._properties['warnings'] + :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. - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + :returns: The created FlowInstance """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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]: """ - return self._properties['date_updated'] + 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 webhook_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 webhook_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[FlowInstance]: """ - return self._properties['webhook_url'] + 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 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 absolute URL of the 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[FlowInstance]: """ - return self._properties['url'] + 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 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[FlowInstance]: """ - return self._properties['links'] + 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. - def update(self, status, friendly_name=values.unset, definition=values.unset, - commit_message=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, + ) -> FlowPage: """ - Update the FlowInstance + Retrieve a single page of FlowInstance records from the API. + Request is executed immediately - :param FlowInstance.Status status: The status of the Flow - :param unicode friendly_name: The string that you assigned to describe the Flow - :param dict definition: JSON representation of flow definition - :param unicode commit_message: Description on change made in the revision + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The updated FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + :returns: Page of FlowInstance """ - return self._proxy.update( - status, - friendly_name=friendly_name, - definition=definition, - commit_message=commit_message, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-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) - 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, + ) -> FlowPage: """ - Fetch the FlowInstance + Asynchronously retrieve a single page of FlowInstance records from the API. + Request is executed immediately - :returns: The fetched FlowInstance - :rtype: twilio.rest.studio.v2.flow.FlowInstance + :param page_token: PageToken provided by the API + :param page_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._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 FlowPage(self._version, response) - def delete(self): + def get_page(self, target_url: str) -> FlowPage: """ - Deletes the FlowInstance + Retrieve a specific page of FlowInstance 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 FlowInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) - @property - def revisions(self): + async def get_page_async(self, target_url: str) -> FlowPage: """ - Access the revisions + 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: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList + :returns: Page of FlowInstance """ - return self._proxy.revisions + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) - @property - def test_users(self): + def get(self, sid: str) -> FlowContext: """ - Access the test_users + Constructs a FlowContext - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserList - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserList + :param sid: The SID of the Flow resource to fetch. """ - return self._proxy.test_users + return FlowContext(self._version, sid=sid) - @property - def executions(self): + def __call__(self, sid: str) -> FlowContext: """ - Access the executions + Constructs a FlowContext - :returns: twilio.rest.studio.v2.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionList + :param sid: The SID of the Flow resource to fetch. """ - return self._proxy.executions + 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/v2/flow/execution/__init__.py b/twilio/rest/studio/v2/flow/execution/__init__.py index 5035cb78f5..c47a3fbbc0 100644 --- a/twilio/rest/studio/v2/flow/execution/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -1,533 +1,738 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.v2.flow.execution.execution_context import ExecutionContextList from twilio.rest.studio.v2.flow.execution.execution_step import ExecutionStepList -class ExecutionList(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 ExecutionList +class ExecutionInstance(InstanceResource): - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow + class Status(object): + ACTIVE = "active" + ENDED = "ended" - :returns: twilio.rest.studio.v2.flow.execution.ExecutionList - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionList - """ - super(ExecutionList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {'flow_sid': flow_sid, } - self._uri = '/Flows/{flow_sid}/Executions'.format(**self._solution) + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None - def stream(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + @property + def _proxy(self) -> "ExecutionContext": """ - 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 Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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) + 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.v2.flow.execution.ExecutionInstance] + :returns: ExecutionContext for this ExecutionInstance """ - 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']) + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context - def list(self, date_created_from=values.unset, date_created_to=values.unset, - limit=None, page_size=None): + def delete(self) -> bool: """ - Lists ExecutionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the ExecutionInstance - :param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v2.flow.execution.ExecutionInstance] + :returns: True if delete succeeds, False otherwise """ - return list(self.stream( - date_created_from=date_created_from, - date_created_to=date_created_to, - limit=limit, - page_size=page_size, - )) + return self._proxy.delete() - def page(self, date_created_from=values.unset, date_created_to=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 ExecutionInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the ExecutionInstance - :param datetime date_created_from: Only show Executions that started on or after this ISO 8601 date-time - :param datetime date_created_to: Only show Executions that started before this ISO 8601 date-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 - :returns: Page of ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionPage + :returns: True if delete succeeds, False otherwise """ - 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, - }) + return await self._proxy.delete_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance - return ExecutionPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched ExecutionInstance """ - Retrieve a specific page of ExecutionInstance 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 ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionPage + async def fetch_async(self) -> "ExecutionInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the ExecutionInstance - return ExecutionPage(self._version, response, self._solution) - def create(self, to, from_, parameters=values.unset): + :returns: The fetched ExecutionInstance """ - Create the ExecutionInstance - - :param unicode to: The Contact phone number to start a Studio Flow Execution - :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Execution - :param dict parameters: JSON data that will be added to the Flow's context + return await self._proxy.fetch_async() - :returns: The created ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ - data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), }) + Update the ExecutionInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + :param status: - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) - def get(self, sid): + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": """ - Constructs a ExecutionContext + Asynchronous coroutine to update the ExecutionInstance - :param sid: The SID of the Execution resource to fetch + :param status: - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + :returns: The updated ExecutionInstance """ - return ExecutionContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, ) + return await self._proxy.update_async( + status=status, + ) - def __call__(self, sid): + @property + def execution_context(self) -> ExecutionContextList: """ - Constructs a ExecutionContext - - :param sid: The SID of the Execution resource to fetch + Access the execution_context + """ + return self._proxy.execution_context - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps """ - return ExecutionContext(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 ExecutionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExecutionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, sid: str): """ - Initialize the ExecutionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow + Initialize the ExecutionContext - :returns: twilio.rest.studio.v2.flow.execution.ExecutionPage - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionPage + :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(ExecutionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ExecutionInstance + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None - :returns: twilio.rest.studio.v2.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + def delete(self) -> bool: """ - return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], ) + Deletes the ExecutionInstance - 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 ExecutionContext(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, flow_sid, sid): + async def delete_async(self) -> bool: """ - Initialize the ExecutionContext + Asynchronous coroutine that deletes the ExecutionInstance - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param sid: The SID of the Execution resource to fetch - :returns: twilio.rest.studio.v2.flow.execution.ExecutionContext - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + :returns: True if delete succeeds, False otherwise """ - super(ExecutionContext, self).__init__(version) - # Path Solution - self._solution = {'flow_sid': flow_sid, 'sid': sid, } - self._uri = '/Flows/{flow_sid}/Executions/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._steps = None - self._execution_context = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ExecutionInstance: """ Fetch the ExecutionInstance + :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def fetch_async(self) -> ExecutionInstance: """ - Deletes the ExecutionInstance + Asynchronous coroutine to fetch the ExecutionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ExecutionInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, status): + 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 ExecutionInstance.Status status: The status of the Execution + :param status: :returns: The updated ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - @property - def steps(self): + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: """ - Access the steps + Asynchronous coroutine to update the ExecutionInstance - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList + :param status: + + :returns: The updated ExecutionInstance """ - if self._steps is None: - self._steps = ExecutionStepList( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['sid'], - ) - return self._steps + + 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): + def execution_context(self) -> ExecutionContextList: """ Access the execution_context - - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList """ if self._execution_context is None: self._execution_context = ExecutionContextList( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['sid'], + self._solution["flow_sid"], + self._solution["sid"], ) return self._execution_context - def __repr__(self): + @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 - :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 ExecutionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExecutionPage(Page): - class Status(object): - ACTIVE = "active" - ENDED = "ended" + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance - def __init__(self, version, payload, flow_sid, sid=None): + :param payload: Payload response from the API """ - Initialize the ExecutionInstance + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) - :returns: twilio.rest.studio.v2.flow.execution.ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + def __repr__(self) -> str: """ - super(ExecutionInstance, self).__init__(version) + Provide a friendly representation - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'contact_channel_address': payload.get('contact_channel_address'), - 'context': payload.get('context'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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 ExecutionList(ListResource): - :returns: ExecutionContext for this ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionContext + def __init__(self, version: Version, flow_sid: str): """ - if self._context is None: - self._context = ExecutionContext( - self._version, - flow_sid=self._solution['flow_sid'], - sid=self._solution['sid'], - ) - return self._context + Initialize the ExecutionList - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode """ - return self._properties['account_sid'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - @property - def contact_channel_address(self): - """ - :returns: The phone number, SIP address or Client identifier that triggered the Execution - :rtype: unicode + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: """ - return self._properties['contact_channel_address'] + Create the ExecutionInstance - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict + :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 """ - return self._properties['context'] - @property - def status(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 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: """ - :returns: The status of the Execution - :rtype: ExecutionInstance.Status + 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 """ - return self._properties['status'] - @property - def date_created(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 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + 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"], + ) - @property - def date_updated(self): + 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + 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"], + ) - @property - def url(self): + 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]: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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]: """ - return self._properties['url'] + 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. - @property - def links(self): + :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: """ - :returns: Nested resource URLs - :rtype: unicode + 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 """ - return self._properties['links'] + 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"}) - def fetch(self): + 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: """ - Fetch the ExecutionInstance + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately - :returns: The fetched ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + :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 """ - return self._proxy.fetch() + 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"}) - def delete(self): + 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: """ - Deletes the ExecutionInstance + Retrieve a specific page of ExecutionInstance 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 ExecutionInstance """ - return self._proxy.delete() + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) - def update(self, status): + async def get_page_async(self, target_url: str) -> ExecutionPage: """ - Update the ExecutionInstance + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately - :param ExecutionInstance.Status status: The status of the Execution + :param target_url: API-generated URL for the requested results page - :returns: The updated ExecutionInstance - :rtype: twilio.rest.studio.v2.flow.execution.ExecutionInstance + :returns: Page of ExecutionInstance """ - return self._proxy.update(status, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) - @property - def steps(self): + def get(self, sid: str) -> ExecutionContext: """ - Access the steps + Constructs a ExecutionContext - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList + :param sid: The SID of the Execution resource to update. """ - return self._proxy.steps + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) - @property - def execution_context(self): + def __call__(self, sid: str) -> ExecutionContext: """ - Access the execution_context + Constructs a ExecutionContext - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList + :param sid: The SID of the Execution resource to update. """ - return self._proxy.execution_context + return ExecutionContext( + 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/v2/flow/execution/execution_context.py b/twilio/rest/studio/v2/flow/execution/execution_context.py index 98f7f5cb21..4c18f81d11 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -1,267 +1,219 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 ExecutionContextList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, flow_sid, execution_sid): + @property + def _proxy(self) -> "ExecutionContextContext": """ - Initialize the ExecutionContextList + 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 SID of the Flow - :param execution_sid: The SID of the Execution + :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 - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextList + def fetch(self) -> "ExecutionContextInstance": """ - super(ExecutionContextList, self).__init__(version) + Fetch the ExecutionContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, } - def get(self): + :returns: The fetched ExecutionContextInstance """ - Constructs a ExecutionContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + async def fetch_async(self) -> "ExecutionContextInstance": """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - ) + Asynchronous coroutine to fetch the ExecutionContextInstance - def __call__(self): - """ - Constructs a ExecutionContextContext - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + :returns: The fetched ExecutionContextInstance """ - return ExecutionContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 ExecutionContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExecutionContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - Initialize the ExecutionContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + Initialize the ExecutionContextContext - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextPage - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextPage + :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(ExecutionContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) - def get_instance(self, payload): + def fetch(self) -> ExecutionContextInstance: """ - Build an instance of ExecutionContextInstance + Fetch the ExecutionContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> ExecutionContextInstance: """ - return '' - + Asynchronous coroutine to fetch the ExecutionContextInstance -class ExecutionContextContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - def __init__(self, version, flow_sid, execution_sid): + :returns: The fetched ExecutionContextInstance """ - Initialize the ExecutionContextContext - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + headers = values.of({}) - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext - """ - super(ExecutionContextContext, self).__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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the ExecutionContextInstance - - :returns: The fetched ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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 ExecutionContextInstance(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, execution_sid): - """ - Initialize the ExecutionContextInstance - - :returns: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance - """ - super(ExecutionContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'context': payload.get('context'), - 'flow_sid': payload.get('flow_sid'), - 'execution_sid': payload.get('execution_sid'), - 'url': payload.get('url'), - } - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_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 ExecutionContextList(ListResource): - :returns: ExecutionContextContext for this ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextContext + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - 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 + Initialize the ExecutionContextList - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def context(self): """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode + def get(self) -> ExecutionContextContext: """ - return self._properties['execution_sid'] + Constructs a ExecutionContextContext - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode """ - return self._properties['url'] + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) - def fetch(self): + def __call__(self) -> ExecutionContextContext: """ - Fetch the ExecutionContextInstance + Constructs a ExecutionContextContext - :returns: The fetched ExecutionContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_context.ExecutionContextInstance """ - return self._proxy.fetch() + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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/v2/flow/execution/execution_step/__init__.py b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py index dfb8b52a1c..9ffb2502e6 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -1,453 +1,498 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.v2.flow.execution.execution_step.execution_step_context import ExecutionStepContextList +from twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) -class ExecutionStepList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, flow_sid, execution_sid): - """ - Initialize the ExecutionStepList +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") - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepList + @property + def _proxy(self) -> "ExecutionStepContext": """ - super(ExecutionStepList, self).__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) + 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: ExecutionStepContext for this 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 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 = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance] + def fetch(self) -> "ExecutionStepInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the ExecutionStepInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the ExecutionStepInstance - :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.v2.flow.execution.execution_step.ExecutionStepInstance] + :returns: The fetched ExecutionStepInstance """ - 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 step_context(self) -> ExecutionStepContextList: """ - Retrieve a single page of ExecutionStepInstance records from the API. - Request is executed immediately + Access the step_context + """ + return self._proxy.step_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 + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage + :returns: Machine friendly representation """ - data = 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(method='GET', uri=self._uri, params=data, ) - return ExecutionStepPage(self._version, response, self._solution) +class ExecutionStepContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ - Retrieve a specific page of ExecutionStepInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page + Initialize the ExecutionStepContext - :returns: Page of ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage + :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. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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 ) - return ExecutionStepPage(self._version, response, self._solution) + self._step_context: Optional[ExecutionStepContextList] = None - def get(self, sid): + def fetch(self) -> ExecutionStepInstance: """ - Constructs a ExecutionStepContext + Fetch the ExecutionStepInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext + :returns: The fetched ExecutionStepInstance """ - return ExecutionStepContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> ExecutionStepInstance: """ - Constructs a ExecutionStepContext + Asynchronous coroutine to fetch the ExecutionStepInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext + :returns: The fetched ExecutionStepInstance """ - return ExecutionStepContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=sid, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + @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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class ExecutionStepPage(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 ExecutionStepPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepPage - """ - super(ExecutionStepPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: """ Build an instance of ExecutionStepInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ExecutionStepContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExecutionStepList(ListResource): - def __init__(self, version, flow_sid, execution_sid, sid): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ - Initialize the ExecutionStepContext + Initialize the ExecutionStepList - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param sid: The unique string that identifies the resource + :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. - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext """ - super(ExecutionStepContext, self).__init__(version) + 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) - - # Dependents - self._step_context = None + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: """ - Fetch the 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. - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return ExecutionStepInstance( - self._version, - payload, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - sid=self._solution['sid'], - ) + return self._version.stream(page, limits["limit"]) - @property - def step_context(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: """ - Access the step_context + 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. - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - """ - if self._step_context is None: - self._step_context = ExecutionStepContextList( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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[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. -class ExecutionStepInstance(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, execution_sid, sid=None): - """ - Initialize the ExecutionStepInstance - - :returns: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance - """ - super(ExecutionStepInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'flow_sid': payload.get('flow_sid'), - 'execution_sid': payload.get('execution_sid'), - 'name': payload.get('name'), - 'context': payload.get('context'), - 'transitioned_from': payload.get('transitioned_from'), - 'transitioned_to': payload.get('transitioned_to'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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, - 'execution_sid': execution_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[ExecutionStepInstance]: """ - 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 ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: ExecutionStepContext for this ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = ExecutionStepContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 unique string that identifies the resource - :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, + ) -> ExecutionStepPage: """ - return self._properties['sid'] + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 SID of the Flow - :rtype: unicode + :returns: Page of ExecutionStepInstance """ - return self._properties['flow_sid'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode - """ - return self._properties['execution_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The event that caused the Flow to transition to the Step - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(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, + ) -> ExecutionStepPage: """ - :returns: The Widget that preceded the Widget for the Step - :rtype: unicode - """ - return self._properties['transitioned_from'] + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately - @property - def transitioned_to(self): - """ - :returns: The Widget that will follow the Widget for the Step - :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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + :returns: Page of ExecutionStepInstance """ - return self._properties['date_created'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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 ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) - @property - def links(self): + async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ - :returns: The URLs of related resources - :rtype: unicode + 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 """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> ExecutionStepContext: """ - Fetch the ExecutionStepInstance + Constructs a ExecutionStepContext - :returns: The fetched ExecutionStepInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.ExecutionStepInstance + :param sid: The SID of the ExecutionStep resource to fetch. """ - return self._proxy.fetch() + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) - @property - def step_context(self): + def __call__(self, sid: str) -> ExecutionStepContext: """ - Access the step_context + Constructs a ExecutionStepContext - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList + :param sid: The SID of the ExecutionStep resource to fetch. """ - return self._proxy.step_context + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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/v2/flow/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py index 74f307eaf3..7f00e0d180 100644 --- 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 @@ -1,284 +1,236 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 ExecutionStepContextList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +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 - def __init__(self, version, flow_sid, execution_sid, step_sid): + @property + def _proxy(self) -> "ExecutionStepContextContext": """ - Initialize the ExecutionStepContextList + 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 SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID + :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 - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextList + def fetch(self) -> "ExecutionStepContextInstance": """ - super(ExecutionStepContextList, self).__init__(version) + Fetch the ExecutionStepContextInstance - # Path Solution - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } - def get(self): + :returns: The fetched ExecutionStepContextInstance """ - Constructs a ExecutionStepContextContext + return self._proxy.fetch() - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + async def fetch_async(self) -> "ExecutionStepContextInstance": """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_sid'], - step_sid=self._solution['step_sid'], - ) + Asynchronous coroutine to fetch the ExecutionStepContextInstance - def __call__(self): - """ - Constructs a ExecutionStepContextContext - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext + :returns: The fetched ExecutionStepContextInstance """ - return ExecutionStepContextContext( - self._version, - flow_sid=self._solution['flow_sid'], - execution_sid=self._solution['execution_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 ExecutionStepContextPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class ExecutionStepContextContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - Initialize the ExecutionStepContextPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID + Initialize the ExecutionStepContextContext - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextPage - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextPage + :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(ExecutionStepContextPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def fetch(self) -> ExecutionStepContextInstance: """ - Build an instance of ExecutionStepContextInstance + Fetch the ExecutionStepContextInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - def __repr__(self): + async def fetch_async(self) -> ExecutionStepContextInstance: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' + Asynchronous coroutine to fetch the ExecutionStepContextInstance -class ExecutionStepContextContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, flow_sid, execution_sid, step_sid): + :returns: The fetched ExecutionStepContextInstance """ - Initialize the ExecutionStepContextContext - - :param Version version: Version that contains the resource - :param flow_sid: The SID of the Flow - :param execution_sid: The SID of the Execution - :param step_sid: Step SID - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - """ - super(ExecutionStepContextContext, self).__init__(version) + headers = values.of({}) - # 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) + headers["Accept"] = "application/json" - def fetch(self): - """ - Fetch the ExecutionStepContextInstance - - :returns: The fetched ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_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 ExecutionStepContextInstance(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, execution_sid, step_sid): - """ - Initialize the ExecutionStepContextInstance - - :returns: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance - """ - super(ExecutionStepContextInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'context': payload.get('context'), - 'execution_sid': payload.get('execution_sid'), - 'flow_sid': payload.get('flow_sid'), - 'step_sid': payload.get('step_sid'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'flow_sid': flow_sid, 'execution_sid': execution_sid, 'step_sid': step_sid, } + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @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: ExecutionStepContextContext for this ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext - """ - 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 +class ExecutionStepContextList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): """ - return self._properties['account_sid'] + Initialize the ExecutionStepContextList - @property - def context(self): - """ - :returns: The current state of the flow - :rtype: dict - """ - return self._properties['context'] + :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. - @property - def execution_sid(self): - """ - :returns: The SID of the Execution - :rtype: unicode """ - return self._properties['execution_sid'] + super().__init__(version) - @property - def flow_sid(self): - """ - :returns: The SID of the Flow - :rtype: unicode - """ - return self._properties['flow_sid'] + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } - @property - def step_sid(self): - """ - :returns: Step SID - :rtype: unicode + def get(self) -> ExecutionStepContextContext: """ - return self._properties['step_sid'] + Constructs a ExecutionStepContextContext - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) - def fetch(self): + def __call__(self) -> ExecutionStepContextContext: """ - Fetch the ExecutionStepContextInstance + Constructs a ExecutionStepContextContext - :returns: The fetched ExecutionStepContextInstance - :rtype: twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance """ - return self._proxy.fetch() + 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): + 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/v2/flow/flow_revision.py b/twilio/rest/studio/v2/flow/flow_revision.py index ad15f9fbd7..aa065074d1 100644 --- a/twilio/rest/studio/v2/flow/flow_revision.py +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -1,402 +1,451 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 -class FlowRevisionList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowRevisionInstance(InstanceResource): - def __init__(self, version, sid): - """ - Initialize the FlowRevisionList + 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") - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource + self._solution = { + "sid": sid, + "revision": revision or self.revision, + } + self._context: Optional[FlowRevisionContext] = None - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList + @property + def _proxy(self) -> "FlowRevisionContext": """ - super(FlowRevisionList, 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 = {'sid': sid, } - self._uri = '/Flows/{sid}/Revisions'.format(**self._solution) + :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 stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the FlowRevisionInstance - :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.v2.flow.flow_revision.FlowRevisionInstance] + :returns: The fetched FlowRevisionInstance """ - 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) -> "FlowRevisionInstance": + """ + Asynchronous coroutine to fetch the FlowRevisionInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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 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.studio.v2.flow.flow_revision.FlowRevisionInstance] + 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 FlowRevisionInstance 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 FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage +class FlowRevisionContext(InstanceContext): + + def __init__(self, version: Version, sid: str, revision: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the FlowRevisionContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return FlowRevisionPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + "revision": revision, + } + self._uri = "/Flows/{sid}/Revisions/{revision}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> FlowRevisionInstance: """ - Retrieve a specific page of FlowRevisionInstance records from the API. - Request is executed immediately + Fetch the FlowRevisionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage + :returns: The fetched FlowRevisionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return FlowRevisionPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, revision): - """ - Constructs a FlowRevisionContext + headers["Accept"] = "application/json" - :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - """ - return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) - def __call__(self, revision): + async def fetch_async(self) -> FlowRevisionInstance: """ - Constructs a FlowRevisionContext + Asynchronous coroutine to fetch the FlowRevisionInstance - :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext + :returns: The fetched FlowRevisionInstance """ - return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) - 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 FlowRevisionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) - def __init__(self, version, response, solution): + def __repr__(self) -> str: """ - Initialize the FlowRevisionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sid: The unique string that identifies the resource + Provide a friendly representation - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage + :returns: Machine friendly representation """ - super(FlowRevisionPage, 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 FlowRevisionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: """ Build an instance of FlowRevisionInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance + :param payload: Payload response from the API """ - return FlowRevisionInstance(self._version, payload, sid=self._solution['sid'], ) + return FlowRevisionInstance(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 '' + return "" -class FlowRevisionContext(InstanceContext): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowRevisionList(ListResource): - def __init__(self, version, sid, revision): + def __init__(self, version: Version, sid: str): """ - Initialize the FlowRevisionContext + Initialize the FlowRevisionList - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext """ - super(FlowRevisionContext, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'sid': sid, 'revision': revision, } - self._uri = '/Flows/{sid}/Revisions/{revision}'.format(**self._solution) + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/Revisions".format(**self._solution) - def fetch(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowRevisionInstance]: """ - Fetch the 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. - :returns: The fetched FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - return FlowRevisionInstance( - self._version, - payload, - sid=self._solution['sid'], - revision=self._solution['revision'], - ) + 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[FlowRevisionInstance]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(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) + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) -class FlowRevisionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + return self._version.stream_async(page, limits["limit"]) - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" + 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. - def __init__(self, version, payload, sid, revision=None): - """ - Initialize the FlowRevisionInstance - - :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance - """ - super(FlowRevisionInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'definition': payload.get('definition'), - 'status': payload.get('status'), - 'revision': deserialize.integer(payload.get('revision')), - 'commit_message': payload.get('commit_message'), - 'valid': payload.get('valid'), - 'errors': payload.get('errors'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 = {'sid': sid, 'revision': revision or self._properties['revision'], } + :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[FlowRevisionInstance]: """ - 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 FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: FlowRevisionContext for this FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = FlowRevisionContext( - self._version, - sid=self._solution['sid'], - revision=self._solution['revision'], + 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 unique string that identifies the resource - :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, + ) -> FlowRevisionPage: """ - return self._properties['sid'] + Retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 string that you assigned to describe the Flow - :rtype: unicode + :returns: Page of FlowRevisionInstance """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def definition(self): - """ - :returns: JSON representation of flow definition - :rtype: dict - """ - return self._properties['definition'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status(self): - """ - :returns: The status of the Flow - :rtype: FlowRevisionInstance.Status - """ - return self._properties['status'] + headers["Accept"] = "application/json" - @property - def revision(self): - """ - :returns: The latest revision number of the Flow's definition - :rtype: unicode - """ - return self._properties['revision'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowRevisionPage(self._version, response, self._solution) - @property - def commit_message(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, + ) -> FlowRevisionPage: """ - :returns: Description on change made in the revision - :rtype: unicode - """ - return self._properties['commit_message'] + Asynchronously retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately - @property - def valid(self): - """ - :returns: Boolean if the flow definition is valid - :rtype: bool - """ - return self._properties['valid'] + :param page_token: PageToken provided by the 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 errors(self): - """ - :returns: List of error in the flow definition - :rtype: dict + :returns: Page of FlowRevisionInstance """ - return self._properties['errors'] + 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 FlowRevisionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FlowRevisionPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - return self._properties['date_created'] + response = self._version.domain.twilio.request("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) - @property - def date_updated(self): + async def get_page_async(self, target_url: str) -> FlowRevisionPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - return self._properties['date_updated'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) - @property - def url(self): + def get(self, revision: str) -> FlowRevisionContext: """ - :returns: The absolute URL of the resource - :rtype: unicode + Constructs a FlowRevisionContext + + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. """ - return self._properties['url'] + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) - def fetch(self): + def __call__(self, revision: str) -> FlowRevisionContext: """ - Fetch the FlowRevisionInstance + Constructs a FlowRevisionContext - :returns: The fetched FlowRevisionInstance - :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. """ - return self._proxy.fetch() + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) - 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/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/test_user.py b/twilio/rest/studio/v2/flow/test_user.py deleted file mode 100644 index edc7628ffc..0000000000 --- a/twilio/rest/studio/v2/flow/test_user.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" - -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 FlowTestUserList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, sid): - """ - Initialize the FlowTestUserList - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserList - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserList - """ - super(FlowTestUserList, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - - def get(self): - """ - Constructs a FlowTestUserContext - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - """ - return FlowTestUserContext(self._version, sid=self._solution['sid'], ) - - def __call__(self): - """ - Constructs a FlowTestUserContext - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - """ - return FlowTestUserContext(self._version, sid=self._solution['sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FlowTestUserPage(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 FlowTestUserPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param sid: The sid - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserPage - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserPage - """ - super(FlowTestUserPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of FlowTestUserInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - return FlowTestUserInstance(self._version, payload, sid=self._solution['sid'], ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class FlowTestUserContext(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 FlowTestUserContext - - :param Version version: Version that contains the resource - :param sid: The sid - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - """ - super(FlowTestUserContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Flows/{sid}/TestUsers'.format(**self._solution) - - def fetch(self): - """ - Fetch the FlowTestUserInstance - - :returns: The fetched FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return FlowTestUserInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, test_users): - """ - Update the FlowTestUserInstance - - :param unicode test_users: The test_users - - :returns: The updated FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - data = values.of({'TestUsers': serialize.map(test_users, lambda e: e), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return FlowTestUserInstance(self._version, payload, 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 FlowTestUserInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, sid): - """ - Initialize the FlowTestUserInstance - - :returns: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - super(FlowTestUserInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'test_users': payload.get('test_users'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'sid': 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: FlowTestUserContext for this FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserContext - """ - if self._context is None: - self._context = FlowTestUserContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: The sid - :rtype: unicode - """ - return self._properties['sid'] - - @property - def test_users(self): - """ - :returns: The test_users - :rtype: unicode - """ - return self._properties['test_users'] - - @property - def url(self): - """ - :returns: The url - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the FlowTestUserInstance - - :returns: The fetched FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - return self._proxy.fetch() - - def update(self, test_users): - """ - Update the FlowTestUserInstance - - :param unicode test_users: The test_users - - :returns: The updated FlowTestUserInstance - :rtype: twilio.rest.studio.v2.flow.test_user.FlowTestUserInstance - """ - return self._proxy.update(test_users, ) - - 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/studio/v2/flow_validate.py b/twilio/rest/studio/v2/flow_validate.py index 22b15e75c8..5f8b308547 100644 --- a/twilio/rest/studio/v2/flow_validate.py +++ b/twilio/rest/studio/v2/flow_validate.py @@ -1,148 +1,143 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ -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 + 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. +""" -class FlowValidateList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version): - """ - Initialize the FlowValidateList - - :param Version version: Version that contains the resource +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values - :returns: twilio.rest.studio.v2.flow_validate.FlowValidateList - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateList - """ - super(FlowValidateList, self).__init__(version) +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - # Path Solution - self._solution = {} - self._uri = '/Flows/Validate'.format(**self._solution) - def update(self, friendly_name, status, definition, - commit_message=values.unset): - """ - Update the FlowValidateInstance +class FlowValidateInstance(InstanceResource): - :param unicode friendly_name: The friendly_name - :param FlowValidateInstance.Status status: The status - :param dict definition: The definition - :param unicode commit_message: The commit_message + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" - :returns: The updated FlowValidateInstance - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateInstance - """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Status': status, - 'Definition': serialize.object(definition), - 'CommitMessage': commit_message, - }) + """ + :ivar valid: Boolean if the flow definition is valid. + """ - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) - return FlowValidateInstance(self._version, payload, ) + self.valid: Optional[bool] = payload.get("valid") - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" -class FlowValidatePage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class FlowValidateList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version): """ - Initialize the FlowValidatePage + Initialize the FlowValidateList - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param version: Version that contains the resource - :returns: twilio.rest.studio.v2.flow_validate.FlowValidatePage - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidatePage """ - super(FlowValidatePage, self).__init__(version, response) + super().__init__(version) - # Path Solution - self._solution = solution + self._uri = "/Flows/Validate" - def get_instance(self, payload): + def update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: """ - Build an instance of FlowValidateInstance + Update the FlowValidateInstance - :param dict payload: Payload response from the API + :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: twilio.rest.studio.v2.flow_validate.FlowValidateInstance - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateInstance + :returns: The created FlowValidateInstance """ - return FlowValidateInstance(self._version, payload, ) - def __repr__(self): - """ - Provide a friendly representation + 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"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" -class FlowValidateInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - class Status(object): - DRAFT = "draft" - PUBLISHED = "published" + return FlowValidateInstance(self._version, payload) - def __init__(self, version, payload): + async def update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: """ - Initialize the 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: twilio.rest.studio.v2.flow_validate.FlowValidateInstance - :rtype: twilio.rest.studio.v2.flow_validate.FlowValidateInstance + :returns: The created FlowValidateInstance """ - super(FlowValidateInstance, self).__init__(version) - # Marshaled Properties - self._properties = {'valid': payload.get('valid'), } + 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"}) - # Context - self._context = None - self._solution = {} + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def valid(self): - """ - :returns: The valid - :rtype: bool - """ - return self._properties['valid'] + 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): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + 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 index 4343fcc152..98928dad6a 100644 --- a/twilio/rest/supersim/__init__.py +++ b/twilio/rest/supersim/__init__.py @@ -1,88 +1,93 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.supersim.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Supersim Domain - - :returns: Domain for Supersim - :rtype: twilio.rest.supersim.Supersim - """ - super(Supersim, self).__init__(twilio) - - self.base_url = 'https://supersim.twilio.com' - - # Versions - self._v1 = None - +class Supersim(SupersimBase): @property - def v1(self): - """ - :returns: Version v1 of supersim - :rtype: twilio.rest.supersim.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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 commands(self): - """ - :rtype: twilio.rest.supersim.v1.command.CommandList - """ - return self.v1.commands + def fleets(self) -> FleetList: + warn( + "fleets is deprecated. Use v1.fleets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.fleets @property - def fleets(self): - """ - :rtype: twilio.rest.supersim.v1.fleet.FleetList - """ - return self.v1.fleets + 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): - """ - :rtype: twilio.rest.supersim.v1.network.NetworkList - """ + 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): - """ - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileList - """ + 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 sims(self): - """ - :rtype: twilio.rest.supersim.v1.sim.SimList - """ - return self.v1.sims + 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 usage_records(self): - """ - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordList - """ - return self.v1.usage_records + 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 + @property + def sms_commands(self) -> SmsCommandList: + warn( + "sms_commands is deprecated. Use v1.sms_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sms_commands - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index dc98db3fdf..2336da2616 100644 --- a/twilio/rest/supersim/v1/__init__.py +++ b/twilio/rest/supersim/v1/__init__.py @@ -1,97 +1,107 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.rest.supersim.v1.command import CommandList +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): + def __init__(self, domain: Domain): """ Initialize the V1 version of Supersim - :returns: V1 version of Supersim - :rtype: twilio.rest.supersim.v1.V1.V1 - """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._commands = None - self._fleets = None - self._networks = None - self._network_access_profiles = None - self._sims = None - self._usage_records = None + :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 commands(self): - """ - :rtype: twilio.rest.supersim.v1.command.CommandList - """ - if self._commands is None: - self._commands = CommandList(self) - return self._commands + def esim_profiles(self) -> EsimProfileList: + if self._esim_profiles is None: + self._esim_profiles = EsimProfileList(self) + return self._esim_profiles @property - def fleets(self): - """ - :rtype: twilio.rest.supersim.v1.fleet.FleetList - """ + def fleets(self) -> FleetList: if self._fleets is None: self._fleets = FleetList(self) return self._fleets @property - def networks(self): - """ - :rtype: twilio.rest.supersim.v1.network.NetworkList - """ + 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): - """ - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileList - """ + 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 sims(self): - """ - :rtype: twilio.rest.supersim.v1.sim.SimList - """ + 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 usage_records(self): - """ - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/supersim/v1/command.py b/twilio/rest/supersim/v1/command.py deleted file mode 100644 index 87dd5099ef..0000000000 --- a/twilio/rest/supersim/v1/command.py +++ /dev/null @@ -1,423 +0,0 @@ -# coding=utf-8 -r""" -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 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 - - :param Version version: Version that contains the resource - - :returns: twilio.rest.supersim.v1.command.CommandList - :rtype: twilio.rest.supersim.v1.command.CommandList - """ - super(CommandList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Commands'.format(**self._solution) - - def create(self, sim, command, callback_method=values.unset, - callback_url=values.unset): - """ - Create the CommandInstance - - :param unicode sim: The sid or unique_name of the SIM to send the Command to - :param unicode command: The message body of the command - :param unicode callback_method: The HTTP method we should use to call callback_url - :param unicode callback_url: The URL we should call after we have sent the command - - :returns: The created CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandInstance - """ - data = values.of({ - 'Sim': sim, - 'Command': command, - 'CallbackMethod': callback_method, - 'CallbackUrl': callback_url, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return CommandInstance(self._version, payload, ) - - def stream(self, sim=values.unset, status=values.unset, direction=values.unset, - limit=None, page_size=None): - """ - 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 sim: The SID or unique name of the Sim that Command was sent to or from. - :param CommandInstance.Status status: The status of the Command - :param CommandInstance.Direction direction: The direction of the Command - :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.supersim.v1.command.CommandInstance] - """ - 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']) - - def list(self, sim=values.unset, status=values.unset, direction=values.unset, - limit=None, page_size=None): - """ - 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 unicode sim: The SID or unique name of the Sim that Command was sent to or from. - :param CommandInstance.Status status: The status of the Command - :param CommandInstance.Direction direction: The direction of the Command - :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.supersim.v1.command.CommandInstance] - """ - return list(self.stream( - sim=sim, - status=status, - direction=direction, - limit=limit, - page_size=page_size, - )) - - def page(self, sim=values.unset, status=values.unset, direction=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of CommandInstance records from the API. - Request is executed immediately - - :param unicode sim: The SID or unique name of the Sim that Command was sent to or from. - :param CommandInstance.Status status: The status of the Command - :param CommandInstance.Direction direction: The direction of the Command - :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.supersim.v1.command.CommandPage - """ - data = values.of({ - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return CommandPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of CommandInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CommandPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a CommandContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.command.CommandContext - :rtype: twilio.rest.supersim.v1.command.CommandContext - """ - return CommandContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a CommandContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.command.CommandContext - :rtype: twilio.rest.supersim.v1.command.CommandContext - """ - return CommandContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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.supersim.v1.command.CommandPage - :rtype: twilio.rest.supersim.v1.command.CommandPage - """ - super(CommandPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of CommandInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.supersim.v1.command.CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandInstance - """ - return CommandInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - 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. """ - - def __init__(self, version, sid): - """ - Initialize the CommandContext - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.command.CommandContext - :rtype: twilio.rest.supersim.v1.command.CommandContext - """ - super(CommandContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Commands/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the CommandInstance - - :returns: The fetched CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return CommandInstance(self._version, payload, 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 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. """ - - class Status(object): - QUEUED = "queued" - SENT = "sent" - DELIVERED = "delivered" - RECEIVED = "received" - FAILED = "failed" - - class Direction(object): - TO_SIM = "to_sim" - FROM_SIM = "from_sim" - - def __init__(self, version, payload, sid=None): - """ - Initialize the CommandInstance - - :returns: twilio.rest.supersim.v1.command.CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandInstance - """ - super(CommandInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'sim_sid': payload.get('sim_sid'), - 'command': payload.get('command'), - 'status': payload.get('status'), - 'direction': payload.get('direction'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: CommandContext for this CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandContext - """ - if self._context is None: - self._context = CommandContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def sim_sid(self): - """ - :returns: The SID of the SIM that this Command was sent to or from - :rtype: unicode - """ - return self._properties['sim_sid'] - - @property - def command(self): - """ - :returns: The message body of the command sent to or from the SIM - :rtype: unicode - """ - return self._properties['command'] - - @property - def status(self): - """ - :returns: The status of the Command - :rtype: CommandInstance.Status - """ - return self._properties['status'] - - @property - def direction(self): - """ - :returns: The direction of the Command - :rtype: CommandInstance.Direction - """ - return self._properties['direction'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The absolute URL of the Command resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the CommandInstance - - :returns: The fetched CommandInstance - :rtype: twilio.rest.supersim.v1.command.CommandInstance - """ - 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/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 index cd607edb1a..3ea067cff2 100644 --- a/twilio/rest/supersim/v1/fleet.py +++ b/twilio/rest/supersim/v1/fleet.py @@ -1,475 +1,727 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 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 +class FleetInstance(InstanceResource): - :param Version version: Version that contains the resource + class DataMetering(object): + PAYG = "payg" - :returns: twilio.rest.supersim.v1.fleet.FleetList - :rtype: twilio.rest.supersim.v1.fleet.FleetList - """ - super(FleetList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/Fleets'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FleetContext] = None - def create(self, network_access_profile, unique_name=values.unset, - data_enabled=values.unset, data_limit=values.unset, - commands_enabled=values.unset, commands_url=values.unset, - commands_method=values.unset): + @property + def _proxy(self) -> "FleetContext": """ - Create the FleetInstance + 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 network_access_profile: The SID or unique name of the Network Access Profile of the Fleet - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param bool data_enabled: Defines whether SIMs in the Fleet are capable of using data connectivity - :param unicode data_limit: The total data usage (download and upload combined) in Megabytes that each Sim resource assigned to the Fleet resource can consume - :param bool commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands - :param unicode commands_url: The URL that will receive a webhook when a SIM in the Fleet originates a machine-to-machine SMS via Commands - :param unicode commands_method: A string representing the HTTP method to use when making a request to `commands_url` + :returns: FleetContext for this FleetInstance + """ + if self._context is None: + self._context = FleetContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + def fetch(self) -> "FleetInstance": """ - data = values.of({ - 'NetworkAccessProfile': network_access_profile, - 'UniqueName': unique_name, - 'DataEnabled': data_enabled, - 'DataLimit': data_limit, - 'CommandsEnabled': commands_enabled, - 'CommandsUrl': commands_url, - 'CommandsMethod': commands_method, - }) + Fetch the FleetInstance - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return FleetInstance(self._version, payload, ) + :returns: The fetched FleetInstance + """ + return self._proxy.fetch() - def stream(self, network_access_profile=values.unset, limit=None, - page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the FleetInstance - :param unicode network_access_profile: The SID or unique name of the Network Access Profile of the Fleet - :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.supersim.v1.fleet.FleetInstance] + :returns: The fetched FleetInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(network_access_profile=network_access_profile, page_size=limits['page_size'], ) + 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 - return self._version.stream(page, limits['limit']) + :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). - def list(self, network_access_profile=values.unset, limit=None, page_size=None): + :returns: The updated 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. + 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, + ) - :param unicode network_access_profile: The SID or unique name of the Network Access Profile of the Fleet - :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, + 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: Generator that will yield up to limit results - :rtype: list[twilio.rest.supersim.v1.fleet.FleetInstance] + :returns: The updated FleetInstance """ - return list(self.stream( + return await self._proxy.update_async( + unique_name=unique_name, network_access_profile=network_access_profile, - limit=limit, - page_size=page_size, - )) + 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 page(self, network_access_profile=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + def __repr__(self) -> str: """ - Retrieve a single page of FleetInstance records from the API. - Request is executed immediately - - :param unicode network_access_profile: The SID or unique name of the Network Access Profile of the Fleet - :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 FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetPage + :returns: Machine friendly representation """ - data = values.of({ - 'NetworkAccessProfile': network_access_profile, - '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(method='GET', uri=self._uri, params=data, ) - return FleetPage(self._version, response, self._solution) +class FleetContext(InstanceContext): - def get_page(self, target_url): + def __init__(self, version: Version, sid: str): """ - 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 + Initialize the FleetContext - :returns: Page of FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetPage + :param version: Version that contains the resource + :param sid: The SID of the Fleet resource to update. """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + super().__init__(version) - return FleetPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Fleets/{sid}".format(**self._solution) - def get(self, sid): + def fetch(self) -> FleetInstance: """ - Constructs a FleetContext + Fetch the FleetInstance - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.supersim.v1.fleet.FleetContext - :rtype: twilio.rest.supersim.v1.fleet.FleetContext + :returns: The fetched FleetInstance """ - return FleetContext(self._version, sid=sid, ) - def __call__(self, sid): - """ - Constructs a FleetContext + headers = values.of({}) - :param sid: The SID that identifies the resource to fetch + headers["Accept"] = "application/json" - :returns: twilio.rest.supersim.v1.fleet.FleetContext - :rtype: twilio.rest.supersim.v1.fleet.FleetContext - """ - return FleetContext(self._version, sid=sid, ) + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def __repr__(self): + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FleetInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the FleetInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched FleetInstance """ - return '' + headers = values.of({}) -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. """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): - """ - Initialize the FleetPage + 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 FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: twilio.rest.supersim.v1.fleet.FleetPage - :rtype: twilio.rest.supersim.v1.fleet.FleetPage + 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: """ - super(FleetPage, self).__init__(version, response) + Update the FleetInstance - # Path Solution - self._solution = solution + :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). - def get_instance(self, payload): + :returns: The updated FleetInstance """ - Build an instance of FleetInstance - :param dict payload: Payload response from the API + 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" - :returns: twilio.rest.supersim.v1.fleet.FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + 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 """ - return FleetInstance(self._version, payload, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -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. """ +class FleetPage(Page): - def __init__(self, version, sid): + def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: """ - Initialize the FleetContext + Build an instance of FleetInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + :param payload: Payload response from the API + """ + return FleetInstance(self._version, payload) - :returns: twilio.rest.supersim.v1.fleet.FleetContext - :rtype: twilio.rest.supersim.v1.fleet.FleetContext + def __repr__(self) -> str: """ - super(FleetContext, self).__init__(version) + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Fleets/{sid}'.format(**self._solution) - def fetch(self): +class FleetList(ListResource): + + def __init__(self, version: Version): """ - Fetch the FleetInstance + Initialize the FleetList + + :param version: Version that contains the resource - :returns: The fetched FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + super().__init__(version) - return FleetInstance(self._version, payload, sid=self._solution['sid'], ) + self._uri = "/Fleets" - def update(self, unique_name=values.unset, network_access_profile=values.unset): + 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: """ - Update the FleetInstance + Create the FleetInstance - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode network_access_profile: The SID or unique name of the Network Access Profile of the Fleet + :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 updated FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + :returns: The created FleetInstance """ - data = values.of({'UniqueName': unique_name, 'NetworkAccessProfile': network_access_profile, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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"}) - return FleetInstance(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 + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -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. """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class DataMetering(object): - PAYG = "payg" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): - """ - Initialize the FleetInstance - - :returns: twilio.rest.supersim.v1.fleet.FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance - """ - super(FleetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'data_enabled': payload.get('data_enabled'), - 'data_limit': deserialize.integer(payload.get('data_limit')), - 'data_metering': payload.get('data_metering'), - 'commands_enabled': payload.get('commands_enabled'), - 'commands_url': payload.get('commands_url'), - 'commands_method': payload.get('commands_method'), - 'network_access_profile_sid': payload.get('network_access_profile_sid'), - } + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + return FleetInstance(self._version, payload) - @property - def _proxy(self): + def stream( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FleetInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: FleetContext for this FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetContext - """ - if self._context is None: - self._context = FleetContext(self._version, sid=self._solution['sid'], ) - return self._context + :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) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + return self._version.stream(page, limits["limit"]) - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + async def stream_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FleetInstance]: """ - return self._properties['unique_name'] + 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. - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + :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) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) - @property - def url(self): - """ - :returns: The absolute URL of the Fleet resource - :rtype: unicode - """ - return self._properties['url'] + return self._version.stream_async(page, limits["limit"]) - @property - def data_enabled(self): + def list( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: """ - :returns: Defines whether SIMs in the Fleet are capable of using data connectivity - :rtype: bool - """ - return self._properties['data_enabled'] + Lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def data_limit(self): - """ - :returns: The total data usage (download and upload combined) in Megabytes that each Sim resource assigned to the Fleet resource can consume - :rtype: unicode - """ - return self._properties['data_limit'] + :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, + ) + ) - @property - def data_metering(self): + async def list_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: """ - :returns: The model by which a SIM is metered and billed - :rtype: FleetInstance.DataMetering - """ - return self._properties['data_metering'] + 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. - @property - def commands_enabled(self): - """ - :returns: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands - :rtype: bool + :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: """ - return self._properties['commands_enabled'] + Retrieve a single page of FleetInstance records from the API. + Request is executed immediately - @property - def commands_url(self): + :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 """ - :returns: The URL that will receive a webhook when a SIM in the Fleet originates a machine-to-machine SMS via Commands - :rtype: unicode + 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: """ - return self._properties['commands_url'] + Asynchronously retrieve a single page of FleetInstance records from the API. + Request is executed immediately - @property - def commands_method(self): + :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 """ - :returns: A string representing the HTTP method to use when making a request to `commands_url` - :rtype: unicode + 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: """ - return self._properties['commands_method'] + Retrieve a specific page of FleetInstance records from the API. + Request is executed immediately - @property - def network_access_profile_sid(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance """ - :returns: The SID of the Network Access Profile of the Fleet - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return FleetPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FleetPage: """ - return self._properties['network_access_profile_sid'] + 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 - def fetch(self): + :returns: Page of FleetInstance """ - Fetch the FleetInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return FleetPage(self._version, response) - :returns: The fetched FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + def get(self, sid: str) -> FleetContext: """ - return self._proxy.fetch() + Constructs a FleetContext - def update(self, unique_name=values.unset, network_access_profile=values.unset): + :param sid: The SID of the Fleet resource to update. """ - Update the FleetInstance + return FleetContext(self._version, sid=sid) - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode network_access_profile: The SID or unique name of the Network Access Profile of the Fleet + def __call__(self, sid: str) -> FleetContext: + """ + Constructs a FleetContext - :returns: The updated FleetInstance - :rtype: twilio.rest.supersim.v1.fleet.FleetInstance + :param sid: The SID of the Fleet resource to update. """ - return self._proxy.update(unique_name=unique_name, network_access_profile=network_access_profile, ) + return FleetContext(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/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 index 100a2c2233..211068d075 100644 --- a/twilio/rest/supersim/v1/network.py +++ b/twilio/rest/supersim/v1/network.py @@ -1,351 +1,460 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 NetworkList(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 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 - def __init__(self, version): + @property + def _proxy(self) -> "NetworkContext": """ - Initialize the NetworkList - - :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.supersim.v1.network.NetworkList - :rtype: twilio.rest.supersim.v1.network.NetworkList + :returns: NetworkContext for this NetworkInstance """ - super(NetworkList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Networks'.format(**self._solution) + if self._context is None: + self._context = NetworkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset, - limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the NetworkInstance - :param unicode iso_country: The ISO country code of the Network resources to read - :param unicode mcc: The MCC of Network resource identifiers to be read - :param unicode mnc: The MNC of Network resource identifiers to be read - :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.supersim.v1.network.NetworkInstance] + :returns: The fetched NetworkInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - page = self.page(iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits['page_size'], ) + async def fetch_async(self) -> "NetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkInstance - return self._version.stream(page, limits['limit']) - def list(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset, - limit=None, page_size=None): + :returns: The fetched 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 unicode iso_country: The ISO country code of the Network resources to read - :param unicode mcc: The MCC of Network resource identifiers to be read - :param unicode mnc: The MNC of Network resource identifiers to be read - :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.supersim.v1.network.NetworkInstance] + def __repr__(self) -> str: """ - return list(self.stream( - iso_country=iso_country, - mcc=mcc, - mnc=mnc, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - def page(self, iso_country=values.unset, mcc=values.unset, mnc=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of NetworkInstance 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 iso_country: The ISO country code of the Network resources to read - :param unicode mcc: The MCC of Network resource identifiers to be read - :param unicode mnc: The MNC of Network resource identifiers to be read - :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 NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkPage +class NetworkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - data = values.of({ - 'IsoCountry': iso_country, - 'Mcc': mcc, - 'Mnc': mnc, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Initialize the NetworkContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :param version: Version that contains the resource + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) - return NetworkPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Networks/{sid}".format(**self._solution) - def get_page(self, target_url): + def fetch(self) -> NetworkInstance: """ - Retrieve a specific page of NetworkInstance records from the API. - Request is executed immediately + Fetch the NetworkInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkPage + :returns: The fetched NetworkInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return NetworkPage(self._version, response, self._solution) + headers = values.of({}) - def get(self, sid): - """ - Constructs a NetworkContext + headers["Accept"] = "application/json" - :param sid: The SID of the Network resource to fetch + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.supersim.v1.network.NetworkContext - :rtype: twilio.rest.supersim.v1.network.NetworkContext - """ - return NetworkContext(self._version, sid=sid, ) + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __call__(self, sid): + async def fetch_async(self) -> NetworkInstance: """ - Constructs a NetworkContext + Asynchronous coroutine to fetch the NetworkInstance - :param sid: The SID of the Network resource to fetch - :returns: twilio.rest.supersim.v1.network.NetworkContext - :rtype: twilio.rest.supersim.v1.network.NetworkContext + :returns: The fetched NetworkInstance """ - return NetworkContext(self._version, sid=sid, ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) class NetworkPage(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): + def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: """ - Initialize the NetworkPage + Build an instance of NetworkInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param payload: Payload response from the API + """ + return NetworkInstance(self._version, payload) - :returns: twilio.rest.supersim.v1.network.NetworkPage - :rtype: twilio.rest.supersim.v1.network.NetworkPage + def __repr__(self) -> str: """ - super(NetworkPage, self).__init__(version, response) + Provide a friendly representation - # Path Solution - self._solution = solution + :returns: Machine friendly representation + """ + return "" + + +class NetworkList(ListResource): - def get_instance(self, payload): + def __init__(self, version: Version): """ - Build an instance of NetworkInstance + Initialize the NetworkList - :param dict payload: Payload response from the API + :param version: Version that contains the resource - :returns: twilio.rest.supersim.v1.network.NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkInstance """ - return NetworkInstance(self._version, payload, ) + super().__init__(version) - def __repr__(self): + 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]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - return '' + 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"]) -class NetworkContext(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. """ + 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. - def __init__(self, version, sid): + :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 """ - Initialize the NetworkContext + 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"] + ) - :param Version version: Version that contains the resource - :param sid: The SID of the Network resource to fetch + return self._version.stream_async(page, limits["limit"]) - :returns: twilio.rest.supersim.v1.network.NetworkContext - :rtype: twilio.rest.supersim.v1.network.NetworkContext + 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]: """ - super(NetworkContext, self).__init__(version) + Lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Networks/{sid}'.format(**self._solution) + :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, + ) + ) - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkInstance + :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: """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + Retrieve a single page of NetworkInstance records from the API. + Request is executed immediately - return NetworkInstance(self._version, payload, sid=self._solution['sid'], ) + :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 - def __repr__(self): + :returns: Page of NetworkInstance """ - Provide a friendly representation + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" -class NetworkInstance(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. """ + 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 - def __init__(self, version, payload, sid=None): - """ - Initialize the NetworkInstance + :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: twilio.rest.supersim.v1.network.NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkInstance + :returns: Page of NetworkInstance """ - super(NetworkInstance, self).__init__(version) + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'url': payload.get('url'), - 'iso_country': payload.get('iso_country'), - 'identifiers': payload.get('identifiers'), - } + headers = values.of({"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 + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) - :returns: NetworkContext for this NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkContext + def get_page(self, target_url: str) -> NetworkPage: """ - if self._context is None: - self._context = NetworkContext(self._version, sid=self._solution['sid'], ) - return self._context + Retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + :param target_url: API-generated URL for the requested results page - @property - def friendly_name(self): - """ - :returns: A human readable identifier of this resource - :rtype: unicode + :returns: Page of NetworkInstance """ - return self._properties['friendly_name'] + response = self._version.domain.twilio.request("GET", target_url) + return NetworkPage(self._version, response) - @property - def url(self): - """ - :returns: The absolute URL of the Network resource - :rtype: unicode + async def get_page_async(self, target_url: str) -> NetworkPage: """ - return self._properties['url'] + Asynchronously retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately - @property - def iso_country(self): - """ - :returns: The ISO country code of the Network resource - :rtype: unicode + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance """ - return self._properties['iso_country'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkPage(self._version, response) - @property - def identifiers(self): + def get(self, sid: str) -> NetworkContext: """ - :returns: The MCC/MNCs included in the Network resource - :rtype: dict + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. """ - return self._properties['identifiers'] + return NetworkContext(self._version, sid=sid) - def fetch(self): + def __call__(self, sid: str) -> NetworkContext: """ - Fetch the NetworkInstance + Constructs a NetworkContext - :returns: The fetched NetworkInstance - :rtype: twilio.rest.supersim.v1.network.NetworkInstance + :param sid: The SID of the Network resource to fetch. """ - return self._proxy.fetch() + return NetworkContext(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/supersim/v1/network_access_profile/__init__.py b/twilio/rest/supersim/v1/network_access_profile/__init__.py index a0015594d9..15b0cc5695 100644 --- a/twilio/rest/supersim/v1/network_access_profile/__init__.py +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -1,417 +1,593 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.supersim.v1.network_access_profile.network_access_profile_network import NetworkAccessProfileNetworkList - - -class NetworkAccessProfileList(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 NetworkAccessProfileList +from twilio.rest.supersim.v1.network_access_profile.network_access_profile_network import ( + NetworkAccessProfileNetworkList, +) - :param Version version: Version that contains the resource - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileList - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileList - """ - super(NetworkAccessProfileList, self).__init__(version) +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") - # Path Solution - self._solution = {} - self._uri = '/NetworkAccessProfiles'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[NetworkAccessProfileContext] = None - def create(self, unique_name=values.unset, networks=values.unset): + @property + def _proxy(self) -> "NetworkAccessProfileContext": """ - Create the NetworkAccessProfileInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode networks: List of Network SIDs that this Network Access Profile will allow connections to + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance + :returns: NetworkAccessProfileContext for this NetworkAccessProfileInstance """ - data = values.of({'UniqueName': unique_name, 'Networks': serialize.map(networks, lambda e: e), }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return NetworkAccessProfileInstance(self._version, payload, ) + if self._context is None: + self._context = NetworkAccessProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def stream(self, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the NetworkAccessProfileInstance - :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.supersim.v1.network_access_profile.NetworkAccessProfileInstance] + :returns: The fetched NetworkAccessProfileInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the NetworkAccessProfileInstance - :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.supersim.v1.network_access_profile.NetworkAccessProfileInstance] + :returns: The fetched NetworkAccessProfileInstance """ - 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, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": """ - Retrieve a single page of NetworkAccessProfileInstance records from the API. - Request is executed immediately + Update the NetworkAccessProfileInstance - :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 unique_name: The new unique name of the Network Access Profile. - :returns: Page of NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfilePage + :returns: The updated NetworkAccessProfileInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return NetworkAccessProfilePage(self._version, response, self._solution) + return self._proxy.update( + unique_name=unique_name, + ) - def get_page(self, target_url): + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": """ - Retrieve a specific page of NetworkAccessProfileInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the NetworkAccessProfileInstance - :param str target_url: API-generated URL for the requested results page + :param unique_name: The new unique name of the Network Access Profile. - :returns: Page of NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfilePage + :returns: The updated NetworkAccessProfileInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + unique_name=unique_name, ) - return NetworkAccessProfilePage(self._version, response, self._solution) - - def get(self, sid): + @property + def networks(self) -> NetworkAccessProfileNetworkList: """ - Constructs a NetworkAccessProfileContext - - :param sid: The SID that identifies the resource to fetch + Access the networks + """ + return self._proxy.networks - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext + def __repr__(self) -> str: """ - return NetworkAccessProfileContext(self._version, sid=sid, ) + Provide a friendly representation - def __call__(self, sid): + :returns: Machine friendly representation """ - Constructs a NetworkAccessProfileContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext - """ - return NetworkAccessProfileContext(self._version, sid=sid, ) +class NetworkAccessProfileContext(InstanceContext): - def __repr__(self): + def __init__(self, version: Version, sid: str): """ - Provide a friendly representation + Initialize the NetworkAccessProfileContext - :returns: Machine friendly representation - :rtype: str + :param version: Version that contains the resource + :param sid: The SID of the Network Access Profile to update. """ - return '' + super().__init__(version) + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/NetworkAccessProfiles/{sid}".format(**self._solution) -class NetworkAccessProfilePage(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. """ + self._networks: Optional[NetworkAccessProfileNetworkList] = None - def __init__(self, version, response, solution): + def fetch(self) -> NetworkAccessProfileInstance: """ - Initialize the NetworkAccessProfilePage + Fetch the NetworkAccessProfileInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfilePage - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfilePage + :returns: The fetched NetworkAccessProfileInstance """ - super(NetworkAccessProfilePage, self).__init__(version, response) - # Path Solution - self._solution = solution + headers = values.of({}) - def get_instance(self, payload): - """ - Build an instance of NetworkAccessProfileInstance + 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.supersim.v1.network_access_profile.NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance - """ - return NetworkAccessProfileInstance(self._version, payload, ) + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __repr__(self): + async def fetch_async(self) -> NetworkAccessProfileInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the NetworkAccessProfileInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched NetworkAccessProfileInstance """ - return '' + headers = values.of({}) -class NetworkAccessProfileContext(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" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + def update( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: """ - Initialize the NetworkAccessProfileContext + Update the NetworkAccessProfileInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch + :param unique_name: The new unique name of the Network Access Profile. - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext + :returns: The updated NetworkAccessProfileInstance """ - super(NetworkAccessProfileContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/NetworkAccessProfiles/{sid}'.format(**self._solution) + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) - # Dependents - self._networks = None + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): - """ - Fetch the NetworkAccessProfileInstance + headers["Accept"] = "application/json" - :returns: The fetched NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - return NetworkAccessProfileInstance(self._version, payload, sid=self._solution['sid'], ) + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) - def update(self, unique_name=values.unset): + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: """ - Update the NetworkAccessProfileInstance + Asynchronous coroutine to update the NetworkAccessProfileInstance - :param unicode unique_name: The new unique name of the resource + :param unique_name: The new unique name of the Network Access Profile. :returns: The updated NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance """ - data = values.of({'UniqueName': unique_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - return NetworkAccessProfileInstance(self._version, payload, sid=self._solution['sid'], ) + 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): + def networks(self) -> NetworkAccessProfileNetworkList: """ Access the networks - - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList """ if self._networks is None: self._networks = NetworkAccessProfileNetworkList( self._version, - network_access_profile_sid=self._solution['sid'], + self._solution["sid"], ) return self._networks - 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 NetworkAccessProfileInstance(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 NetworkAccessProfilePage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: """ - Initialize the NetworkAccessProfileInstance + Build an instance of NetworkAccessProfileInstance - :returns: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance + :param payload: Payload response from the API """ - super(NetworkAccessProfileInstance, self).__init__(version) + return NetworkAccessProfileInstance(self._version, payload) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: Machine friendly representation + """ + return "" - @property - def _proxy(self): + +class NetworkAccessProfileList(ListResource): + + 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 NetworkAccessProfileList + + :param version: Version that contains the resource - :returns: NetworkAccessProfileContext for this NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileContext """ - if self._context is None: - self._context = NetworkAccessProfileContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def sid(self): + self._uri = "/NetworkAccessProfiles" + + def create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def unique_name(self): + 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: """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + 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 """ - return self._properties['unique_name'] - @property - def account_sid(self): + 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]: """ - :returns: The SID of the Account that the Network Access Profile belongs to - :rtype: unicode + 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 """ - 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[NetworkAccessProfileInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - 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[NetworkAccessProfileInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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 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[NetworkAccessProfileInstance]: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 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, + ) -> NetworkAccessProfilePage: """ - :returns: The links - :rtype: unicode + 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 """ - 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"}) - def fetch(self): + 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: """ - Fetch the NetworkAccessProfileInstance + Asynchronously retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately - :returns: The fetched NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 NetworkAccessProfilePage(self._version, response) - def update(self, unique_name=values.unset): + def get_page(self, target_url: str) -> NetworkAccessProfilePage: """ - Update the NetworkAccessProfileInstance + Retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately - :param unicode unique_name: The new unique name of the resource + :param target_url: API-generated URL for the requested results page - :returns: The updated NetworkAccessProfileInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.NetworkAccessProfileInstance + :returns: Page of NetworkAccessProfileInstance """ - return self._proxy.update(unique_name=unique_name, ) + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfilePage(self._version, response) - @property - def networks(self): + async def get_page_async(self, target_url: str) -> NetworkAccessProfilePage: """ - Access the networks + 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: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList + :returns: Page of NetworkAccessProfileInstance """ - return self._proxy.networks + 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): + 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/supersim/v1/network_access_profile/network_access_profile_network.py b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py index 8591030c0b..c7099b8a7a 100644 --- 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 @@ -1,399 +1,557 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 NetworkAccessProfileNetworkList(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 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 - def __init__(self, version, network_access_profile_sid): + @property + def _proxy(self) -> "NetworkAccessProfileNetworkContext": """ - Initialize the NetworkAccessProfileNetworkList + 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 network_access_profile_sid: The unique string that identifies the Network Access Profile resource + :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 - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkList + def delete(self) -> bool: """ - super(NetworkAccessProfileNetworkList, self).__init__(version) + Deletes the NetworkAccessProfileNetworkInstance - # Path Solution - self._solution = {'network_access_profile_sid': network_access_profile_sid, } - self._uri = '/NetworkAccessProfiles/{network_access_profile_sid}/Networks'.format(**self._solution) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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 NetworkAccessProfileNetworkInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance] + + :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) -> "NetworkAccessProfileNetworkInstance": + """ + Fetch the NetworkAccessProfileNetworkInstance - return self._version.stream(page, limits['limit']) - def list(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance - :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.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance] + :returns: The fetched NetworkAccessProfileNetworkInstance """ - 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 NetworkAccessProfileNetworkInstance records from the API. - Request is executed immediately + Provide a friendly representation - :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 NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkPage + +class NetworkAccessProfileNetworkContext(InstanceContext): + + def __init__(self, version: Version, network_access_profile_sid: str, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the NetworkAccessProfileNetworkContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + # 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 get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. - Request is executed immediately + Deletes the NetworkAccessProfileNetworkInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def create(self, network): + async def delete_async(self) -> bool: """ - Create the NetworkAccessProfileNetworkInstance + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance - :param unicode network: The SID that identifies the Network resource - :returns: The created NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Network': network, }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) - return NetworkAccessProfileNetworkInstance( - self._version, - payload, - network_access_profile_sid=self._solution['network_access_profile_sid'], + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers ) - def get(self, sid): + def fetch(self) -> NetworkAccessProfileNetworkInstance: """ - Constructs a NetworkAccessProfileNetworkContext + Fetch the NetworkAccessProfileNetworkInstance - :param sid: The SID of the resource to fetch - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext + :returns: The fetched NetworkAccessProfileNetworkInstance """ - return NetworkAccessProfileNetworkContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkAccessProfileNetworkInstance( self._version, - network_access_profile_sid=self._solution['network_access_profile_sid'], - sid=sid, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: """ - Constructs a NetworkAccessProfileNetworkContext + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance - :param sid: The SID of the resource to fetch - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext + :returns: The fetched NetworkAccessProfileNetworkInstance """ - return NetworkAccessProfileNetworkContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( self._version, - network_access_profile_sid=self._solution['network_access_profile_sid'], - sid=sid, + payload, + network_access_profile_sid=self._solution["network_access_profile_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 NetworkAccessProfileNetworkPage(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 NetworkAccessProfileNetworkPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource - - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkPage - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkPage - """ - super(NetworkAccessProfileNetworkPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): + def get_instance( + self, payload: Dict[str, Any] + ) -> NetworkAccessProfileNetworkInstance: """ Build an instance of NetworkAccessProfileNetworkInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance + :param payload: Payload response from the API """ return NetworkAccessProfileNetworkInstance( self._version, payload, - network_access_profile_sid=self._solution['network_access_profile_sid'], + network_access_profile_sid=self._solution["network_access_profile_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class NetworkAccessProfileNetworkContext(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 NetworkAccessProfileNetworkList(ListResource): - def __init__(self, version, network_access_profile_sid, sid): + def __init__(self, version: Version, network_access_profile_sid: str): """ - Initialize the NetworkAccessProfileNetworkContext + Initialize the NetworkAccessProfileNetworkList - :param Version 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 resource to fetch + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext """ - super(NetworkAccessProfileNetworkContext, self).__init__(version) + 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) + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks".format( + **self._solution + ) + ) - def delete(self): + def create(self, network: str) -> NetworkAccessProfileNetworkInstance: """ - Deletes the NetworkAccessProfileNetworkInstance + Create the NetworkAccessProfileNetworkInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + :param network: The SID of the Network resource to be added to the Network Access Profile resource. - def fetch(self): + :returns: The created NetworkAccessProfileNetworkInstance """ - Fetch the NetworkAccessProfileNetworkInstance - :returns: The fetched NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], - sid=self._solution['sid'], + network_access_profile_sid=self._solution["network_access_profile_sid"], ) - def __repr__(self): + async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: """ - Provide a friendly representation + Asynchronously create the NetworkAccessProfileNetworkInstance - :returns: Machine friendly representation - :rtype: str + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "Network": network, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) -class NetworkAccessProfileNetworkInstance(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["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload, network_access_profile_sid, sid=None): - """ - Initialize the NetworkAccessProfileNetworkInstance + 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"], + ) - :returns: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileNetworkInstance]: """ - super(NetworkAccessProfileNetworkInstance, self).__init__(version) + 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. - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'network_access_profile_sid': payload.get('network_access_profile_sid'), - 'friendly_name': payload.get('friendly_name'), - 'iso_country': payload.get('iso_country'), - 'identifiers': payload.get('identifiers'), - 'url': payload.get('url'), - } + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - # Context - self._context = None - self._solution = { - 'network_access_profile_sid': network_access_profile_sid, - 'sid': sid or self._properties['sid'], - } + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def _proxy(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileNetworkInstance]: """ - 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 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. - :returns: NetworkAccessProfileNetworkContext for this NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkContext + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 = NetworkAccessProfileNetworkContext( - self._version, - network_access_profile_sid=self._solution['network_access_profile_sid'], - sid=self._solution['sid'], - ) - return self._context + 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[NetworkAccessProfileNetworkInstance]: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 self._properties['sid'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def network_access_profile_sid(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: """ - :returns: The unique string that identifies the Network Access Profile resource - :rtype: unicode + 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 self._properties['network_access_profile_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, + ) -> NetworkAccessProfileNetworkPage: """ - :returns: A human readable identifier of this resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def iso_country(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 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: """ - :returns: The ISO country code of the Network resource - :rtype: unicode + 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 """ - return self._properties['iso_country'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def identifiers(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 NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: """ - :returns: The MCC/MNCs included in the resource - :rtype: dict + 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 """ - return self._properties['identifiers'] + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) - @property - def url(self): + async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> NetworkAccessProfileNetworkContext: """ - Deletes the NetworkAccessProfileNetworkInstance + Constructs a NetworkAccessProfileNetworkContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Network resource to fetch. """ - return self._proxy.delete() + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) - def fetch(self): + def __call__(self, sid: str) -> NetworkAccessProfileNetworkContext: """ - Fetch the NetworkAccessProfileNetworkInstance + Constructs a NetworkAccessProfileNetworkContext - :returns: The fetched NetworkAccessProfileNetworkInstance - :rtype: twilio.rest.supersim.v1.network_access_profile.network_access_profile_network.NetworkAccessProfileNetworkInstance + :param sid: The SID of the Network resource to fetch. """ - return self._proxy.fetch() + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_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/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.py b/twilio/rest/supersim/v1/sim.py deleted file mode 100644 index 9e672693e9..0000000000 --- a/twilio/rest/supersim/v1/sim.py +++ /dev/null @@ -1,426 +0,0 @@ -# coding=utf-8 -r""" -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 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.supersim.v1.sim.SimList - :rtype: twilio.rest.supersim.v1.sim.SimList - """ - super(SimList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/Sims'.format(**self._solution) - - def stream(self, status=values.unset, fleet=values.unset, iccid=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 SimInstance.Status status: The status of the Sim resources to read - :param unicode fleet: The SID or unique name of the Fleet to which a list of Sims are assigned - :param unicode iccid: The ICCID associated with a Super SIM to filter the list by - :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.supersim.v1.sim.SimInstance] - """ - 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']) - - def list(self, status=values.unset, fleet=values.unset, iccid=values.unset, - limit=None, page_size=None): - """ - 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 - :param unicode fleet: The SID or unique name of the Fleet to which a list of Sims are assigned - :param unicode iccid: The ICCID associated with a Super SIM to filter the list by - :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.supersim.v1.sim.SimInstance] - """ - return list(self.stream(status=status, fleet=fleet, iccid=iccid, limit=limit, page_size=page_size, )) - - def page(self, status=values.unset, fleet=values.unset, iccid=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): - """ - Retrieve a single page of SimInstance records from the API. - Request is executed immediately - - :param SimInstance.Status status: The status of the Sim resources to read - :param unicode fleet: The SID or unique name of the Fleet to which a list of Sims are assigned - :param unicode iccid: The ICCID associated with a Super SIM to filter the list by - :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.supersim.v1.sim.SimPage - """ - data = values.of({ - 'Status': status, - 'Fleet': fleet, - 'Iccid': iccid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SimPage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - 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 - - :returns: Page of SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimPage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return SimPage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a SimContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.sim.SimContext - :rtype: twilio.rest.supersim.v1.sim.SimContext - """ - return SimContext(self._version, sid=sid, ) - - def __call__(self, sid): - """ - Constructs a SimContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.sim.SimContext - :rtype: twilio.rest.supersim.v1.sim.SimContext - """ - return SimContext(self._version, sid=sid, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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. """ - - def __init__(self, version, response, solution): - """ - Initialize the SimPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.supersim.v1.sim.SimPage - :rtype: twilio.rest.supersim.v1.sim.SimPage - """ - super(SimPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SimInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.supersim.v1.sim.SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - return SimInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -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. """ - - def __init__(self, version, sid): - """ - Initialize the SimContext - - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.supersim.v1.sim.SimContext - :rtype: twilio.rest.supersim.v1.sim.SimContext - """ - super(SimContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the SimInstance - - :returns: The fetched SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SimInstance(self._version, payload, sid=self._solution['sid'], ) - - def update(self, unique_name=values.unset, status=values.unset, - fleet=values.unset): - """ - Update the SimInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param SimInstance.StatusUpdate status: The new status of the Super SIM - :param unicode fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned - - :returns: The updated SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - data = values.of({'UniqueName': unique_name, 'Status': status, 'Fleet': fleet, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SimInstance(self._version, payload, 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 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. """ - - class Status(object): - NEW = "new" - READY = "ready" - ACTIVE = "active" - INACTIVE = "inactive" - SCHEDULED = "scheduled" - - class StatusUpdate(object): - READY = "ready" - ACTIVE = "active" - INACTIVE = "inactive" - - def __init__(self, version, payload, sid=None): - """ - Initialize the SimInstance - - :returns: twilio.rest.supersim.v1.sim.SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - super(SimInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'iccid': payload.get('iccid'), - 'status': payload.get('status'), - 'fleet_sid': payload.get('fleet_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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: SimContext for this SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimContext - """ - if self._context is None: - self._context = SimContext(self._version, sid=self._solution['sid'], ) - return self._context - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that the Super SIM belongs to - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def iccid(self): - """ - :returns: The ICCID associated with the SIM - :rtype: unicode - """ - return self._properties['iccid'] - - @property - def status(self): - """ - :returns: The status of the Super SIM - :rtype: SimInstance.Status - """ - return self._properties['status'] - - @property - def fleet_sid(self): - """ - :returns: The unique ID of the Fleet configured for this SIM - :rtype: unicode - """ - return self._properties['fleet_sid'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def url(self): - """ - :returns: The absolute URL of the Sim Resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the SimInstance - - :returns: The fetched SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - return self._proxy.fetch() - - def update(self, unique_name=values.unset, status=values.unset, - fleet=values.unset): - """ - Update the SimInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param SimInstance.StatusUpdate status: The new status of the Super SIM - :param unicode fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned - - :returns: The updated SimInstance - :rtype: twilio.rest.supersim.v1.sim.SimInstance - """ - return self._proxy.update(unique_name=unique_name, status=status, fleet=fleet, ) - - 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/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 index 199402dae6..94072a51fb 100644 --- a/twilio/rest/supersim/v1/usage_record.py +++ b/twilio/rest/supersim/v1/usage_record.py @@ -1,302 +1,458 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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_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): - """ 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): + def __init__(self, version: Version): """ Initialize the UsageRecordList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordList - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordList """ - super(UsageRecordList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/UsageRecords'.format(**self._solution) + self._uri = "/UsageRecords" - def stream(self, sim=values.unset, granularity=values.unset, - start_time=values.unset, end_time=values.unset, limit=None, - page_size=None): + 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 unicode sim: SID of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. - :param UsageRecordInstance.Granularity granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. - :param datetime start_time: Only include usage that occurred at or after this time. - :param datetime end_time: Only include usage that occurred before this 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 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 - :rtype: list[twilio.rest.supersim.v1.usage_record.UsageRecordInstance] """ 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'], + page_size=limits["page_size"], ) - return self._version.stream(page, limits['limit']) - - def list(self, sim=values.unset, granularity=values.unset, - start_time=values.unset, end_time=values.unset, limit=None, - page_size=None): - """ - Lists UsageRecordInstance 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, + 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 unicode sim: SID of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. - :param UsageRecordInstance.Granularity granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. - :param datetime start_time: Only include usage that occurred at or after this time. - :param datetime end_time: Only include usage that occurred before this 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 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 - :rtype: list[twilio.rest.supersim.v1.usage_record.UsageRecordInstance] """ - return list(self.stream( + 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, - limit=limit, - page_size=page_size, - )) - - def page(self, sim=values.unset, granularity=values.unset, - start_time=values.unset, end_time=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 - - :param unicode sim: SID of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. - :param UsageRecordInstance.Granularity granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. - :param datetime start_time: Only include usage that occurred at or after this time. - :param datetime end_time: Only include usage that occurred before this 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 + page_size=limits["page_size"], + ) - :returns: Page of UsageRecordInstance - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordPage + 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]: """ - data = values.of({ - 'Sim': sim, - 'Granularity': granularity, - 'StartTime': serialize.iso8601_datetime(start_time), - 'EndTime': serialize.iso8601_datetime(end_time), - '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(method='GET', uri=self._uri, params=data, ) + :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, + ) + ) - return UsageRecordPage(self._version, response, self._solution) + 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. - def get_page(self, target_url): + :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 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 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 - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, + } ) - 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 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 UsageRecordPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordPage - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordPage - """ - super(UsageRecordPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of UsageRecordInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :param dict payload: Payload response from the API + headers["Accept"] = "application/json" - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordInstance - """ - return UsageRecordInstance(self._version, payload, ) + 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 - def __repr__(self): - """ - Provide a friendly representation + :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: Machine friendly representation - :rtype: str + :returns: Page of UsageRecordInstance """ - return '' - - -class UsageRecordInstance(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 Granularity(object): - HOUR = "hour" - DAY = "day" - ALL = "all" - - class Group(object): - SIM = "sim" + 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, + } + ) - class SortBy(object): - TIME = "time" + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class SortOrder(object): - DESC = "desc" - ASC = "asc" + headers["Accept"] = "application/json" - def __init__(self, version, payload): - """ - Initialize the UsageRecordInstance + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) - :returns: twilio.rest.supersim.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.supersim.v1.usage_record.UsageRecordInstance + def get_page(self, target_url: str) -> UsageRecordPage: """ - super(UsageRecordInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sim_sid': payload.get('sim_sid'), - 'period': payload.get('period'), - 'data_upload': deserialize.integer(payload.get('data_upload')), - 'data_download': deserialize.integer(payload.get('data_download')), - 'data_total': deserialize.integer(payload.get('data_total')), - } - - # Context - self._context = None - self._solution = {} - - @property - def account_sid(self): - """ - :returns: The SID of the Account that incurred the usage. - :rtype: unicode - """ - return self._properties['account_sid'] + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def sim_sid(self): - """ - :returns: SID of a Sim resource to which the UsageRecord belongs. - :rtype: unicode - """ - return self._properties['sim_sid'] + :param target_url: API-generated URL for the requested results page - @property - def period(self): - """ - :returns: The time period for which the usage is reported. - :rtype: dict + :returns: Page of UsageRecordInstance """ - return self._properties['period'] + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response) - @property - def data_upload(self): - """ - :returns: Total data uploaded in bytes, aggregated by the query parameters. - :rtype: unicode + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - return self._properties['data_upload'] + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def data_download(self): - """ - :returns: Total data downloaded in bytes, aggregated by the query parameters. - :rtype: unicode - """ - return self._properties['data_download'] + :param target_url: API-generated URL for the requested results page - @property - def data_total(self): - """ - :returns: Total of data_upload and data_download. - :rtype: unicode + :returns: Page of UsageRecordInstance """ - return self._properties['data_total'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response) - 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/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 8592f0fbfa..37b9ce03d6 100644 --- a/twilio/rest/sync/__init__.py +++ b/twilio/rest/sync/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -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 aaf86f5c69..e98201bd41 100644 --- a/twilio/rest/sync/v1/__init__.py +++ b/twilio/rest/sync/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 9650e9b651..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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,598 +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, - reachability_debouncing_enabled=values.unset, - reachability_debouncing_window=values.unset, - webhooks_from_rest_enabled=values.unset): + :returns: ServiceContext for this ServiceInstance """ - Create the ServiceInstance - - :param unicode friendly_name: A string that you assign to describe the resource - :param unicode webhook_url: The URL we should call when Sync objects are manipulated - :param bool reachability_webhooks_enabled: Whether the service instance should call webhook_url when client endpoints connect to Sync - :param bool acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource - :param bool reachability_debouncing_enabled: Whether every endpoint_disconnected event occurs after a configurable delay - :param unicode reachability_debouncing_window: The reachability event delay in milliseconds - :param bool webhooks_from_rest_enabled: Whether the Service instance should call webhook_url when the REST API is used to update Sync objects + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The 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, - 'ReachabilityDebouncingEnabled': reachability_debouncing_enabled, - 'ReachabilityDebouncingWindow': reachability_debouncing_window, - 'WebhooksFromRestEnabled': webhooks_from_rest_enabled, - }) - - payload = self._version.create(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ServicePage(self._version, response, self._solution) + return await self._proxy.fetch_async() - 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`. - def get(self, sid): + :returns: The updated ServiceInstance """ - Constructs a ServiceContext - - :param sid: The SID of the Service resource to fetch + 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, + ) - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + @property + def documents(self) -> DocumentList: """ - return ServiceContext(self._version, sid=sid, ) + Access the documents + """ + 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 of the Service resource to fetch + @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: """ - return ServiceContext(self._version, sid=sid, ) + Access the sync_streams + """ + 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 - - 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._documents: Optional[DocumentList] = None + self._sync_lists: Optional[SyncListList] = None + self._sync_maps: Optional[SyncMapList] = None + self._sync_streams: Optional[SyncStreamList] = None - :returns: twilio.rest.sync.v1.service.ServiceInstance - :rtype: twilio.rest.sync.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 of the Service resource to fetch - :returns: twilio.rest.sync.v1.service.ServiceContext - :rtype: twilio.rest.sync.v1.service.ServiceContext + :returns: True if delete succeeds, False otherwise """ - 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 + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ServiceInstance: """ Fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.sync.v1.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + 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"], + ) - def delete(self): + async def fetch_async(self) -> ServiceInstance: """ - Deletes the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ServiceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, acl_enabled=values.unset, - reachability_debouncing_enabled=values.unset, - reachability_debouncing_window=values.unset, - webhooks_from_rest_enabled=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ Update the ServiceInstance - :param unicode webhook_url: The URL we should call when Sync objects are manipulated - :param unicode friendly_name: A string that you assign to describe the resource - :param bool reachability_webhooks_enabled: Whether the service instance should call webhook_url when client endpoints connect to Sync - :param bool acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource - :param bool reachability_debouncing_enabled: Whether every endpoint_disconnected event occurs after a configurable delay - :param unicode reachability_debouncing_window: The reachability event delay in milliseconds - :param bool webhooks_from_rest_enabled: Whether the Service instance should call webhook_url when the REST API is used to update Sync objects + :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 - :rtype: twilio.rest.sync.v1.service.ServiceInstance """ - data = values.of({ - 'WebhookUrl': webhook_url, - 'FriendlyName': friendly_name, - 'ReachabilityWebhooksEnabled': reachability_webhooks_enabled, - 'AclEnabled': acl_enabled, - 'ReachabilityDebouncingEnabled': reachability_debouncing_enabled, - 'ReachabilityDebouncingWindow': reachability_debouncing_window, - 'WebhooksFromRestEnabled': webhooks_from_rest_enabled, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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" - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) @property - def documents(self): + 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'webhook_url': payload.get('webhook_url'), - 'webhooks_from_rest_enabled': payload.get('webhooks_from_rest_enabled'), - 'reachability_webhooks_enabled': payload.get('reachability_webhooks_enabled'), - 'acl_enabled': payload.get('acl_enabled'), - 'reachability_debouncing_enabled': payload.get('reachability_debouncing_enabled'), - 'reachability_debouncing_window': deserialize.integer(payload.get('reachability_debouncing_window')), - 'links': payload.get('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): + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] +class ServiceList(ListResource): - @property - def date_created(self): + def __init__(self, version: Version): """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + Initialize the ServiceList - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + :param version: Version that contains the resource - @property - def url(self): - """ - :returns: The absolute URL of the Service resource - :rtype: unicode """ - return self._properties['url'] + super().__init__(version) - @property - def webhook_url(self): - """ - :returns: The URL we call when Sync objects are manipulated - :rtype: unicode - """ - return self._properties['webhook_url'] + self._uri = "/Services" - @property - def webhooks_from_rest_enabled(self): - """ - :returns: Whether the Service instance should call webhook_url when the REST API is used to update Sync objects - :rtype: bool + 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: """ - return self._properties['webhooks_from_rest_enabled'] + Create the ServiceInstance - @property - def reachability_webhooks_enabled(self): - """ - :returns: Whether the service instance calls webhook_url when client endpoints connect to Sync - :rtype: bool - """ - return self._properties['reachability_webhooks_enabled'] + :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`. - @property - def acl_enabled(self): - """ - :returns: Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource - :rtype: bool + :returns: The created ServiceInstance """ - return self._properties['acl_enabled'] - @property - def reachability_debouncing_enabled(self): + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance """ - :returns: Whether every endpoint_disconnected event occurs after a configurable delay - :rtype: bool + + 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_debouncing_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 reachability_debouncing_window(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 reachability event delay in milliseconds - :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['reachability_debouncing_window'] + 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 URLs of related resources - :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 the ServiceInstance + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - :returns: The 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"}) + + headers["Accept"] = "application/json" - def update(self, webhook_url=values.unset, friendly_name=values.unset, - reachability_webhooks_enabled=values.unset, acl_enabled=values.unset, - reachability_debouncing_enabled=values.unset, - reachability_debouncing_window=values.unset, - webhooks_from_rest_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 unicode webhook_url: The URL we should call when Sync objects are manipulated - :param unicode friendly_name: A string that you assign to describe the resource - :param bool reachability_webhooks_enabled: Whether the service instance should call webhook_url when client endpoints connect to Sync - :param bool acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource - :param bool reachability_debouncing_enabled: Whether every endpoint_disconnected event occurs after a configurable delay - :param unicode reachability_debouncing_window: The reachability event delay in milliseconds - :param bool webhooks_from_rest_enabled: Whether the Service instance should call webhook_url when the REST API is used to update Sync objects + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The 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, - reachability_debouncing_enabled=reachability_debouncing_enabled, - reachability_debouncing_window=reachability_debouncing_window, - webhooks_from_rest_enabled=webhooks_from_rest_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 - :returns: twilio.rest.sync.v1.service.document.DocumentList - :rtype: twilio.rest.sync.v1.service.document.DocumentList + :param target_url: API-generated URL for the requested results page + + :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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.sync.v1.service.sync_list.SyncListList - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListList + :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 e82831b51f..fe64f629a8 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -1,506 +1,723 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Sync Service that the resource is associated with + 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 the DocumentInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the Sync Document - :param dict data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores - :param unicode ttl: How long, in seconds, before the Sync Document expires and is deleted + if self._context is None: + self._context = DocumentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The 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(method='POST', uri=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. + 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) - - :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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 of the Document resource to fetch + :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 of the Document resource to fetch - - :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 SID of the Sync Service that the resource is associated with + 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 SID of the Sync Service with the Document resource to fetch - :param sid: The SID of the Document resource to fetch - :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 the DocumentInstance + Asynchronous coroutine to fetch the DocumentInstance + :returns: The fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, if_match=values.unset): + 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 - :param unicode if_match: The If-Match HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated DocumentInstance """ - headers = values.of({'If-Match': if_match, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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" - def update(self, data=values.unset, ttl=values.unset, if_match=values.unset): + 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: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores - :param unicode ttl: How long, in seconds, before the Document resource expires and is deleted - :param unicode if_match: The If-Match HTTP request header + :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 - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance """ - data = values.of({'Data': serialize.object(data), 'Ttl': ttl, }) - headers = values.of({'If-Match': if_match, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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): + def __repr__(self) -> str: """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def service_sid(self): +class DocumentList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode + 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. + """ - 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}/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: """ - :returns: The absolute URL of the Document resource - :rtype: unicode + Create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance """ - return self._properties['url'] - @property - def links(self): + 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: """ - :returns: The URLs of resources related to the Sync Document - :rtype: unicode + Asynchronously create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance """ - return self._properties['links'] - @property - def revision(self): + 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]: """ - :returns: The current revision of the Sync Document, represented by a string identifier - :rtype: unicode + Streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['revision'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def data(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DocumentInstance]: """ - :returns: An arbitrary, schema-less object that the Sync Document stores - :rtype: dict + Asynchronously streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['data'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def date_expires(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: """ - :returns: The ISO 8601 date and time in GMT when the Sync Document expires - :rtype: datetime + Lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return self._properties['date_expires'] + 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[DocumentInstance]: """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + Asynchronously lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results """ - return 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, + ) -> DocumentPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance """ - return self._properties['date_updated'] + data = values.of( + { + "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 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: """ - :returns: The identity of the Sync Document's creator - :rtype: unicode + Asynchronously retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance """ - 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, self._solution) - def fetch(self): + def get_page(self, target_url: str) -> DocumentPage: """ - Fetch the DocumentInstance + Retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately - :returns: The fetched DocumentInstance - :rtype: twilio.rest.sync.v1.service.document.DocumentInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPage(self._version, response, self._solution) - def delete(self, if_match=values.unset): + async def get_page_async(self, target_url: str) -> DocumentPage: """ - Deletes the DocumentInstance + Asynchronously retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately - :param unicode if_match: The If-Match HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of DocumentInstance """ - return self._proxy.delete(if_match=if_match, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPage(self._version, response, self._solution) - def update(self, data=values.unset, ttl=values.unset, if_match=values.unset): + def get(self, sid: str) -> DocumentContext: """ - Update the DocumentInstance - - :param dict data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores - :param unicode ttl: How long, in seconds, before the Document resource expires and is deleted - :param unicode if_match: The If-Match HTTP request header + Constructs a DocumentContext - :returns: The 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, if_match=if_match, ) + 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 2a0c0d2d86..75a27c969a 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -1,439 +1,617 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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. """ - - def __init__(self, version, service_sid, document_sid): - """ - Initialize the DocumentPermissionList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Sync Service that the resource is associated with - :param document_sid: The Sync Document SID + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity or self.identity, + } + self._context: Optional[DocumentPermissionContext] = None - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionList + @property + def _proxy(self) -> "DocumentPermissionContext": """ - 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) + 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: DocumentPermissionContext for this DocumentPermissionInstance """ - Streams DocumentPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param 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 = DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the DocumentPermissionInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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 DocumentPermissionInstance 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 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: 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) -> "DocumentPermissionInstance": """ - Retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately + 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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return DocumentPermissionPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "DocumentPermissionInstance": """ - Retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the DocumentPermissionInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage + :returns: The fetched DocumentPermissionInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return DocumentPermissionPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, identity): + def update( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": """ - Constructs a DocumentPermissionContext + Update the DocumentPermissionInstance - :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to fetch + :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 self._proxy.update( + read=read, + write=write, + manage=manage, ) - def __call__(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: The application-defined string that uniquely identifies the User's Document Permission resource to fetch + :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 __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 DocumentPermissionPage(Page): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class DocumentPermissionContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__( + self, version: Version, service_sid: str, document_sid: str, identity: str + ): """ - Initialize the DocumentPermissionPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Sync Service that the resource is associated with - :param document_sid: The Sync Document SID + Initialize the DocumentPermissionContext - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionPage + :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(DocumentPermissionPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of DocumentPermissionInstance + Deletes 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: True if delete succeeds, False otherwise """ - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_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 DocumentPermissionInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class DocumentPermissionContext(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, document_sid, identity): + def fetch(self) -> DocumentPermissionInstance: """ - Initialize the DocumentPermissionContext + Fetch the DocumentPermissionInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Sync Service with the Document Permission resource to fetch - :param document_sid: The SID of the Sync Document with the Document Permission resource to fetch - :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to fetch - :returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext + :returns: The fetched DocumentPermissionInstance """ - 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) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) - def fetch(self): + async def fetch_async(self) -> DocumentPermissionInstance: """ - Fetch the DocumentPermissionInstance + Asynchronous coroutine to fetch the DocumentPermissionInstance + :returns: The fetched DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) return DocumentPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - def delete(self): + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: """ - Deletes the DocumentPermissionInstance + Update the DocumentPermissionInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, read, write, manage): + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: """ - Update the DocumentPermissionInstance + Asynchronous coroutine to update the DocumentPermissionInstance - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. :returns: The updated DocumentPermissionInstance - :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return DocumentPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - document_sid=self._solution['document_sid'], - identity=self._solution['identity'], + 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.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'document_sid': payload.get('document_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('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: The SID of the Account that created the resource - :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: The SID of the Sync Service that the resource is associated with - :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: The 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: The 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: The absolute URL of the Sync Document Permission 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance """ - Fetch the DocumentPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) - :returns: The 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: The 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 78359ad825..1b8e54aff8 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -1,516 +1,723 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Sync Service that the resource is associated with + 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) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Lists'.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, - collection_ttl=values.unset): + :returns: SyncListContext for this SyncListInstance """ - Create the SyncListInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode ttl: Alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync List expires and is deleted + if self._context is None: + self._context = SyncListContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The created SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + def delete(self) -> bool: """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, 'CollectionTtl': collection_ttl, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_list.SyncListInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the SyncListInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + 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 self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncListInstance": """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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 - :returns: Page of SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage + :returns: The fetched SyncListInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SyncListPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + 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 + 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 self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncListPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": """ - Constructs a SyncListContext + Asynchronous coroutine to update the SyncListInstance - :param sid: The SID of the Sync List resource to fetch + :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: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + :returns: The updated SyncListInstance """ - return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) - def __call__(self, sid): + @property + def sync_list_items(self) -> SyncListItemList: """ - Constructs a SyncListContext - - :param sid: The SID of the Sync List resource to fetch + Access the sync_list_items + """ + return self._proxy.sync_list_items - :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext + @property + def sync_list_permissions(self) -> SyncListPermissionList: + """ + 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 SID of the Sync Service that the resource is associated with + 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 SID of the Sync Service with the Sync List resource to fetch - :param sid: The SID of the Sync List resource to fetch - :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({}) + + headers["Accept"] = "application/json" - # Dependents - self._sync_list_items = None - self._sync_list_permissions = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncListInstance: """ - Fetch the SyncListInstance + Asynchronous coroutine to fetch the SyncListInstance + :returns: The fetched SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=self._uri, ) - def update(self, ttl=values.unset, collection_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: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync List expires and is deleted + :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 - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance """ - data = values.of({'Ttl': ttl, 'CollectionTtl': collection_ttl, }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 SID of the Sync Service that the resource is associated with - :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 absolute URL of the Sync List resource - :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 URLs of the Sync List's nested resources - :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 current revision of the Sync List, represented as a string - :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 ISO 8601 date and time in GMT when the Sync List 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 identity of the Sync List's creator - :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 the SyncListInstance + Asynchronously retrieve a single page of SyncListInstance records from the API. + Request is executed immediately - :returns: The 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, + } + ) - 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 SyncListPage(self._version, response, self._solution) + + 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, collection_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: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync List expires and is deleted + :param target_url: API-generated URL for the requested results page - :returns: The updated SyncListInstance - :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance + :returns: Page of SyncListInstance """ - return self._proxy.update(ttl=ttl, collection_ttl=collection_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 090aa336e0..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,548 +1,835 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Sync Service that the resource is associated with - :param list_sid: The SID of the Sync List that contains the List Item + 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, item_ttl=values.unset, - collection_ttl=values.unset): + @property + def _proxy(self) -> "SyncListItemContext": """ - Create the 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: A JSON string that represents an arbitrary, schema-less object that the List Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the List Item expires - :param unicode collection_ttl: How long, in seconds, before the List Item's parent Sync List expires + :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: The 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, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) + Deletes the SyncListItemInstance - payload = self._version.create(method='POST', uri=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 to return the List Items - :param unicode from_: The index of the first Sync List Item resource to read - :param SyncListItemInstance.QueryFromBoundType bounds: Whether to include the List Item referenced by the from parameter - :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) - - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return await self._proxy.delete_async( + if_match=if_match, + ) - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + def fetch(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. + Fetch the SyncListItemInstance - :param SyncListItemInstance.QueryResultOrder order: The order to return the List Items - :param unicode from_: The index of the first Sync List Item resource to read - :param SyncListItemInstance.QueryFromBoundType bounds: Whether to include the List Item referenced by the from parameter - :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 self._proxy.fetch() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncListItemInstance": """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SyncListItemInstance - :param SyncListItemInstance.QueryResultOrder order: The order to return the List Items - :param unicode from_: The index of the first Sync List Item resource to read - :param SyncListItemInstance.QueryFromBoundType bounds: Whether to include the List Item referenced by the from parameter - :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.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :returns: The fetched SyncListItemInstance """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Update the SyncListItemInstance - return SyncListItemPage(self._version, response, 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 get_page(self, target_url): + :returns: The updated SyncListItemInstance """ - Retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemPage + :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 """ - 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 of the Sync List Item resource to fetch - :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 of the Sync List Item resource to fetch + :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 SID of the Sync Service that the resource is associated with - :param list_sid: The SID of the Sync List that contains the List Item - :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 SID of the Sync Service with the Sync List Item resource to fetch - :param list_sid: The SID of the Sync List with the Sync List Item resource to fetch - :param index: The index of the Sync List Item resource to fetch + 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 the SyncListItemInstance - :returns: The fetched SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return SyncListItemInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - index=self._solution['index'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - def delete(self, if_match=values.unset): + 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: """ - Deletes the SyncListItemInstance + Asynchronous coroutine to update the SyncListItemInstance - :param unicode if_match: The If-Match HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated SyncListItemInstance """ - headers = values.of({'If-Match': if_match, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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, item_ttl=values.unset, - collection_ttl=values.unset, if_match=values.unset): - """ - Update the SyncListItemInstance + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :param dict data: A JSON string that represents an arbitrary, schema-less object that the List Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the List Item expires - :param unicode collection_ttl: How long, in seconds, before the List Item's parent Sync List expires - :param unicode if_match: The If-Match HTTP request header + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: The updated SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance - """ - data = values.of({ - 'Data': serialize.object(data), - 'Ttl': ttl, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) - headers = values.of({'If-Match': if_match, }) + headers["Accept"] = "application/json" - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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.get('index')), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'list_sid': payload.get('list_sid'), - 'url': payload.get('url'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 automatically generated index of the List Item - :rtype: unicode """ - return self._properties['index'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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): + 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: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Create the SyncListItemInstance - @property - def list_sid(self): - """ - :returns: The SID of the Sync List that contains the List Item - :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 absolute URL of the List Item resource - :rtype: unicode + :returns: The created SyncListItemInstance """ - return self._properties['url'] - @property - def revision(self): - """ - :returns: The current revision of the item, represented as a string - :rtype: unicode + 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: """ - return self._properties['revision'] + Asynchronously create the SyncListItemInstance - @property - def data(self): + :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 """ - :returns: An arbitrary, schema-less object that the List Item stores - :rtype: dict + + 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]: """ - return self._properties['data'] + 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. - @property - def date_expires(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 ISO 8601 date and time in GMT when the List Item expires - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListItemInstance]: """ - return self._properties['date_expires'] + 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. - @property - def date_created(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListItemInstance]: """ - return self._properties['date_created'] + 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 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists SyncListItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListItemPage: """ - return self._properties['date_updated'] + Retrieve a single page of SyncListItemInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 identity of the List Item's creator - :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 = 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 """ - return self._properties['created_by'] + 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 fetch(self): + def get_page(self, target_url: str) -> SyncListItemPage: """ - Fetch the SyncListItemInstance + Retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately - :returns: The fetched SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) - def delete(self, if_match=values.unset): + async def get_page_async(self, target_url: str) -> SyncListItemPage: """ - Deletes the SyncListItemInstance + Asynchronously retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately - :param unicode if_match: The If-Match HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of SyncListItemInstance """ - return self._proxy.delete(if_match=if_match, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) - def update(self, data=values.unset, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset, if_match=values.unset): + def get(self, index: int) -> SyncListItemContext: """ - Update the SyncListItemInstance + Constructs a SyncListItemContext - :param dict data: A JSON string that represents an arbitrary, schema-less object that the List Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the List Item expires - :param unicode collection_ttl: How long, in seconds, before the List Item's parent Sync List expires - :param unicode if_match: The If-Match HTTP request header + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) - :returns: The updated SyncListItemInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_item.SyncListItemInstance + def __call__(self, index: int) -> SyncListItemContext: """ - return self._proxy.update( - data=data, - ttl=ttl, - item_ttl=item_ttl, - collection_ttl=collection_ttl, - if_match=if_match, + Constructs a SyncListItemContext + + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, ) - def __repr__(self): + 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 c6dff7707c..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,439 +1,617 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - def __init__(self, version, service_sid, list_sid): + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncListPermissionContext] = None + + @property + def _proxy(self) -> "SyncListPermissionContext": """ - 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: The SID of the Sync Service that the resource is associated with - :param list_sid: The SID of the Sync List to which the Permission applies + :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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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: The application-defined string that uniquely identifies the User's Sync List Permission resource to fetch + :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: The application-defined string that uniquely identifies the User's Sync List Permission resource to fetch - :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: The SID of the Sync Service that the resource is associated with - :param list_sid: The SID of the Sync List to which the Permission applies - :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" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, list_sid, identity): + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: """ - Initialize the SyncListPermissionContext + Update the SyncListPermissionInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Sync Service with the Sync List Permission resource to fetch - :param list_sid: The SID of the Sync List with the Sync List Permission resource to fetch - :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to fetch + :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 """ - 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) + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def fetch(self): + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: """ - Fetch the SyncListPermissionInstance + Asynchronous coroutine to update the SyncListPermissionInstance - :returns: The fetched SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return SyncListPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the SyncListPermissionInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def update(self, read, write, manage): - """ - Update the SyncListPermissionInstance - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access +class SyncListPermissionPage(Page): - :returns: The updated SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance + def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Build an instance of SyncListPermissionInstance + :param payload: Payload response from the API + """ return SyncListPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - list_sid=self._solution['list_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_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 SyncListPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncListPermissionList(ListResource): - def __init__(self, version, payload, service_sid, list_sid, identity=None): + def __init__(self, version: Version, service_sid: str, list_sid: str): """ - Initialize the SyncListPermissionInstance + Initialize the SyncListPermissionList - :returns: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance - """ - super(SyncListPermissionInstance, self).__init__(version) + :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`. - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'list_sid': payload.get('list_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'list_sid': list_sid, - 'identity': identity or self._properties['identity'], + "service_sid": service_sid, + "list_sid": list_sid, } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Permissions".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListPermissionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: SyncListPermissionContext for this SyncListPermissionInstance - :rtype: twilio.rest.sync.v1.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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 SID of the Account that created the resource - :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 service_sid(self): - """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + return self._version.stream(page, limits["limit"]) - @property - def list_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListPermissionInstance]: """ - :returns: The SID of the Sync List to which the Permission applies - :rtype: unicode - """ - 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: The 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: The absolute URL of the Sync List Permission 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance """ - Fetch the SyncListPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) - :returns: The 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: The 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 6eaa6620f2..c6bb1ce556 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -1,516 +1,723 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Sync Service that the resource is associated with + 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) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Maps'.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, - collection_ttl=values.unset): + :returns: SyncMapContext for this SyncMapInstance """ - Create the SyncMapInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode ttl: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync Map expires and is deleted + if self._context is None: + self._context = SyncMapContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The created SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + def delete(self) -> bool: """ - data = values.of({'UniqueName': unique_name, 'Ttl': ttl, 'CollectionTtl': collection_ttl, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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 self._proxy.delete() - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.sync.v1.service.sync_map.SyncMapInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the SyncMapInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + 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 self._proxy.fetch() - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncMapInstance": """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch 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 - :returns: Page of SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapPage + :returns: The fetched SyncMapInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SyncMapPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + 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 + 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 self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, ) - return SyncMapPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": """ - Constructs a SyncMapContext + Asynchronous coroutine to update the SyncMapInstance - :param sid: The SID of the Sync Map resource to fetch + :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: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + :returns: The updated SyncMapInstance """ - return SyncMapContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) - def __call__(self, sid): + @property + def sync_map_items(self) -> SyncMapItemList: """ - Constructs a SyncMapContext - - :param sid: The SID of the Sync Map resource to fetch + Access the sync_map_items + """ + return self._proxy.sync_map_items - :returns: twilio.rest.sync.v1.service.sync_map.SyncMapContext - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapContext + @property + def sync_map_permissions(self) -> SyncMapPermissionList: + """ + 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 SID of the Sync Service that the resource is associated with + 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 SID of the Sync Service with the Sync Map resource to fetch - :param sid: The SID of the Sync Map resource to fetch - :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({}) + + headers["Accept"] = "application/json" - # Dependents - self._sync_map_items = None - self._sync_map_permissions = None + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self): + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncMapInstance: """ - Fetch the SyncMapInstance + Asynchronous coroutine to fetch the SyncMapInstance + :returns: The fetched SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=self._uri, ) - def update(self, ttl=values.unset, collection_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: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync Map expires and is deleted + :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 - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance """ - data = values.of({'Ttl': ttl, 'CollectionTtl': collection_ttl, }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'revision': payload.get('revision'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['unique_name'] + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 SID of the Sync Service that the resource is associated with - :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 absolute URL of the Sync Map resource - :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 URLs of the Sync Map's nested resources - :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 current revision of the Sync Map, represented as a string - :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 ISO 8601 date and time in GMT when the Sync Map 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 identity of the Sync Map's creator - :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 the SyncMapInstance + Asynchronously retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately - :returns: The 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, + } + ) - 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 SyncMapPage(self._version, response, self._solution) + + 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, collection_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: An alias for collection_ttl - :param unicode collection_ttl: How long, in seconds, before the Sync Map expires and is deleted + :param target_url: API-generated URL for the requested results page - :returns: The updated SyncMapInstance - :rtype: twilio.rest.sync.v1.service.sync_map.SyncMapInstance + :returns: Page of SyncMapInstance """ - return self._proxy.update(ttl=ttl, collection_ttl=collection_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 707e2a7d1d..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,550 +1,841 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Sync Service that the resource is associated with - :param map_sid: The SID of the Sync Map that contains the Map Item + 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, item_ttl=values.unset, - collection_ttl=values.unset): + @property + def _proxy(self) -> "SyncMapItemContext": """ - Create the 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 unique, user-defined key for the Map Item - :param dict data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the Map Item expires - :param unicode collection_ttl: How long, in seconds, before the Map Item's parent Sync Map expires and is deleted + :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: The 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, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) + Deletes the SyncMapItemInstance - payload = self._version.create(method='POST', uri=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: How to order the Map Items returned by their key value - :param unicode from_: The index of the first Sync Map Item resource to read - :param SyncMapItemInstance.QueryFromBoundType bounds: Whether to include the Map Item referenced by the from parameter - :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) - - page = self.page(order=order, from_=from_, bounds=bounds, page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return await self._proxy.delete_async( + if_match=if_match, + ) - def list(self, order=values.unset, from_=values.unset, bounds=values.unset, - limit=None, page_size=None): + def fetch(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. + Fetch the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: How to order the Map Items returned by their key value - :param unicode from_: The index of the first Sync Map Item resource to read - :param SyncMapItemInstance.QueryFromBoundType bounds: Whether to include the Map Item referenced by the from parameter - :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 self._proxy.fetch() - def page(self, order=values.unset, from_=values.unset, bounds=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + async def fetch_async(self) -> "SyncMapItemInstance": """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the SyncMapItemInstance - :param SyncMapItemInstance.QueryResultOrder order: How to order the Map Items returned by their key value - :param unicode from_: The index of the first Sync Map Item resource to read - :param SyncMapItemInstance.QueryFromBoundType bounds: Whether to include the Map Item referenced by the from parameter - :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.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :returns: The fetched SyncMapItemInstance """ - data = values.of({ - 'Order': order, - 'From': from_, - 'Bounds': bounds, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Update the SyncMapItemInstance - return SyncMapItemPage(self._version, response, 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 get_page(self, target_url): + :returns: The updated SyncMapItemInstance """ - Retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) - :param str target_url: API-generated URL for the requested results page + 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 - :returns: Page of SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemPage + :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 """ - 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 value of the Sync Map Item resource to fetch - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemContext +class SyncMapItemContext(InstanceContext): + + 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 value of the Sync Map Item resource to fetch + :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 SID of the Sync Service that the resource is associated with - :param map_sid: The SID of the Sync Map that contains the Map Item - :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 SID of the Sync Service with the Sync Map Item resource to fetch - :param map_sid: The SID of the Sync Map with the Sync Map Item resource to fetch - :param key: The key value of the Sync Map Item resource to fetch + 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 the SyncMapItemInstance - :returns: The fetched SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return SyncMapItemInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - key=self._solution['key'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - def delete(self, if_match=values.unset): + 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: """ - Deletes the SyncMapItemInstance + Asynchronous coroutine to update the SyncMapItemInstance - :param unicode if_match: The If-Match HTTP request header + :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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated SyncMapItemInstance """ - headers = values.of({'If-Match': if_match, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + 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, item_ttl=values.unset, - collection_ttl=values.unset, if_match=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: A JSON string that represents an arbitrary, schema-less object that the Map Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the Map Item expires - :param unicode collection_ttl: How long, in seconds, before the Map Item's parent Sync Map expires and is deleted - :param unicode if_match: The If-Match HTTP request header + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: The updated SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance - """ - data = values.of({ - 'Data': serialize.object(data), - 'Ttl': ttl, - 'ItemTtl': item_ttl, - 'CollectionTtl': collection_ttl, - }) - headers = values.of({'If-Match': if_match, }) + headers["Accept"] = "application/json" - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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.get('key'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'map_sid': payload.get('map_sid'), - 'url': payload.get('url'), - 'revision': payload.get('revision'), - 'data': payload.get('data'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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 unique, user-defined key for the Map Item - :rtype: unicode """ - return self._properties['key'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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): + 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: """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + Create the SyncMapItemInstance - @property - def map_sid(self): - """ - :returns: The SID of the Sync Map that contains the Map Item - :rtype: unicode - """ - return self._properties['map_sid'] + :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. - @property - def url(self): - """ - :returns: The absolute URL of the Map Item resource - :rtype: unicode + :returns: The created SyncMapItemInstance """ - return self._properties['url'] - @property - def revision(self): - """ - :returns: The current revision of the Map Item, represented as a string - :rtype: unicode + data = values.of( + { + "Key": key, + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + async def create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: """ - return self._properties['revision'] + Asynchronously create the SyncMapItemInstance - @property - def data(self): + :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 """ - :returns: An arbitrary, schema-less object that the Map Item stores - :rtype: dict + + 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]: """ - return self._properties['data'] + 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. - @property - def date_expires(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 ISO 8601 date and time in GMT when the Map Item expires - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapItemInstance]: """ - return self._properties['date_expires'] + 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. - @property - def date_created(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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapItemInstance]: """ - return self._properties['date_created'] + 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 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]: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + Asynchronously lists SyncMapItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapItemPage: """ - return self._properties['date_updated'] + Retrieve a single page of SyncMapItemInstance records from the API. + Request is executed immediately - @property - def created_by(self): + :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 identity of the Map Item's creator - :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 = 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 """ - return self._properties['created_by'] + 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 fetch(self): + def get_page(self, target_url: str) -> SyncMapItemPage: """ - Fetch the SyncMapItemInstance + Retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately - :returns: The fetched SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) - def delete(self, if_match=values.unset): + async def get_page_async(self, target_url: str) -> SyncMapItemPage: """ - Deletes the SyncMapItemInstance + Asynchronously retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately - :param unicode if_match: The If-Match HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of SyncMapItemInstance """ - return self._proxy.delete(if_match=if_match, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) - def update(self, data=values.unset, ttl=values.unset, item_ttl=values.unset, - collection_ttl=values.unset, if_match=values.unset): + def get(self, key: str) -> SyncMapItemContext: """ - Update the SyncMapItemInstance + Constructs a SyncMapItemContext - :param dict data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores - :param unicode ttl: An alias for item_ttl - :param unicode item_ttl: How long, in seconds, before the Map Item expires - :param unicode collection_ttl: How long, in seconds, before the Map Item's parent Sync Map expires and is deleted - :param unicode if_match: The If-Match HTTP request header + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) - :returns: The updated SyncMapItemInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_item.SyncMapItemInstance + def __call__(self, key: str) -> SyncMapItemContext: """ - return self._proxy.update( - data=data, - ttl=ttl, - item_ttl=item_ttl, - collection_ttl=collection_ttl, - if_match=if_match, + Constructs a SyncMapItemContext + + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, ) - def __repr__(self): + 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 fe487b884d..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,439 +1,615 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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") - def __init__(self, version, service_sid, map_sid): + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncMapPermissionContext] = None + + @property + def _proxy(self) -> "SyncMapPermissionContext": """ - 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: The SID of the Sync Service that the resource is associated with - :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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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: The application-defined string that uniquely identifies the User's Sync Map Permission resource to fetch + :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: The application-defined string that uniquely identifies the User's Sync Map Permission resource to fetch - :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: The SID of the Sync Service that the resource is associated with - :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" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, map_sid, identity): + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: """ - Initialize the SyncMapPermissionContext + Update the SyncMapPermissionInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Sync Service with the Sync Map Permission resource to fetch - :param map_sid: The SID of the Sync Map with the Sync Map Permission resource to fetch - :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to fetch + :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 """ - 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) + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - def fetch(self): + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: """ - Fetch the SyncMapPermissionInstance + Asynchronous coroutine to update the SyncMapPermissionInstance - :returns: The fetched SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return SyncMapPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the SyncMapPermissionInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def update(self, read, write, manage): - """ - Update the SyncMapPermissionInstance - :param bool read: Read access - :param bool write: Write access - :param bool manage: Manage access +class SyncMapPermissionPage(Page): - :returns: The updated SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance + def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: """ - data = values.of({'Read': read, 'Write': write, 'Manage': manage, }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + Build an instance of SyncMapPermissionInstance + :param payload: Payload response from the API + """ return SyncMapPermissionInstance( self._version, payload, - service_sid=self._solution['service_sid'], - map_sid=self._solution['map_sid'], - identity=self._solution['identity'], + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_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 SyncMapPermissionInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ +class SyncMapPermissionList(ListResource): - def __init__(self, version, payload, service_sid, map_sid, identity=None): + def __init__(self, version: Version, service_sid: str, map_sid: str): """ - Initialize the SyncMapPermissionInstance + Initialize the SyncMapPermissionList - :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance - """ - super(SyncMapPermissionInstance, self).__init__(version) + :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`. - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'map_sid': payload.get('map_sid'), - 'identity': payload.get('identity'), - 'read': payload.get('read'), - 'write': payload.get('write'), - 'manage': payload.get('manage'), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'map_sid': map_sid, - 'identity': identity or self._properties['identity'], + "service_sid": service_sid, + "map_sid": map_sid, } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Permissions".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapPermissionInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: SyncMapPermissionContext for this SyncMapPermissionInstance - :rtype: twilio.rest.sync.v1.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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 SID of the Account that created the resource - :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 service_sid(self): - """ - :returns: The SID of the Sync Service that the resource is associated with - :rtype: unicode - """ - return self._properties['service_sid'] + return self._version.stream(page, limits["limit"]) - @property - def map_sid(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapPermissionInstance]: """ - :returns: Sync Map SID - :rtype: unicode - """ - 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: The 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[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: The absolute URL of the Sync Map Permission 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 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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance """ - Fetch the SyncMapPermissionInstance + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) - :returns: The 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: The 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 4d8ed0d0eb..a7f4128e05 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -1,475 +1,671 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the Sync Service that the resource is associated with + 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 the SyncStreamInstance - - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode ttl: How long, in seconds, before the Stream expires and is deleted + if self._context is None: + self._context = SyncStreamContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The 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(method='POST', uri=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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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: The SID of the Stream resource to fetch + :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: The SID of the Stream resource to fetch - - :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: The SID of the Sync Service that the resource is associated with + 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 SID of the Sync Service with the Sync Stream resource to fetch - :param sid: The SID of the Stream resource to fetch - :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({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._stream_messages = None + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> SyncStreamInstance: """ - Fetch the SyncStreamInstance + Asynchronous coroutine to fetch the SyncStreamInstance + :returns: The fetched SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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: How long, in seconds, before the Stream expires and is deleted + :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 - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance """ - data = values.of({'Ttl': ttl, }) - payload = self._version.update(method='POST', uri=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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'created_by': payload.get('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: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def unique_name(self): + :returns: Machine friendly representation """ - :returns: An application-defined string that uniquely identifies the resource - :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: The SID of the Account that created the resource - :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: The SID of the Sync Service that the resource is associated with - :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: The absolute URL of the Message Stream resource - :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: The URLs of the Stream's nested resources - :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 ISO 8601 date and time in GMT when the Message 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 ISO 8601 date and time in GMT when the 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[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 ISO 8601 date and time in GMT when the resource was last 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: The Identity of the Stream's 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 + + :param page_token: PageToken provided by the 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 SyncStreamInstance """ - Fetch the SyncStreamInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched SyncStreamInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncStreamPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncStreamPage: """ - return self._proxy.fetch() + Retrieve a specific page of SyncStreamInstance 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 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: How long, in seconds, before the Stream expires and is deleted + def get(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext - :returns: The 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 b2a155e469..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,157 +1,146 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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: The SID of the Sync Service that the resource is associated with - :param stream_sid: The unique string that identifies the resource + :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 the StreamMessageInstance - :param dict data: A JSON string that represents an arbitrary, schema-less object that makes up the 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: The created StreamMessageInstance - :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance """ - data = values.of({'Data': serialize.object(data), }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return StreamMessageInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - stream_sid=self._solution['stream_sid'], + data = values.of( + { + "Data": serialize.object(data), + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def __repr__(self): - """ - Provide a friendly representation + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) -class StreamMessagePage(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 StreamMessagePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Sync Service that the resource is associated with - :param stream_sid: The unique string that identifies the resource - - :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) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of StreamMessageInstance - - :param dict payload: Payload response from the API - - :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): + async def create_async(self, data: object) -> StreamMessageInstance: """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - + Asynchronously create the StreamMessageInstance -class StreamMessageInstance(InstanceResource): - """ 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, payload, service_sid, stream_sid): + :returns: The created StreamMessageInstance """ - 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) + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Marshaled Properties - self._properties = {'sid': payload.get('sid'), 'data': payload.get('data'), } + headers["Content-Type"] = "application/x-www-form-urlencoded" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'stream_sid': stream_sid, } + headers["Accept"] = "application/json" - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def data(self): - """ - :returns: Stream Message body - :rtype: dict - """ - return self._properties['data'] + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_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/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 0724e54d04..73d3ee8250 100644 --- a/twilio/rest/taskrouter/__init__.py +++ b/twilio/rest/taskrouter/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -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 091bb146d5..a17eeccc2a 100644 --- a/twilio/rest/taskrouter/v1/__init__.py +++ b/twilio/rest/taskrouter/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 957a3d0d54..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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,760 +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 of the Workspace resources to read - :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']) + :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 of the Workspace resources to read - :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 of the Workspace resources to read - :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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() + + 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 str target_url: API-generated URL for the requested results page + :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: Page of WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspacePage + :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: - 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): + :returns: The updated WorkspaceInstance """ - Create the 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, + ) - :param unicode friendly_name: A string to describe the Workspace resource - :param unicode event_callback_url: The URL we should call when an event occurs - :param unicode events_filter: The list of Workspace events for which to call event_callback_url - :param bool multi_task_enabled: Whether multi-tasking is enabled - :param unicode template: An available template name - :param WorkspaceInstance.QueueOrder prioritize_queue_order: The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + return self._proxy.activities - :returns: The 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(method='POST', uri=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 of the resource to fetch + @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 of the resource to fetch + @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 of the resource to fetch - :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): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkspaceInstance: """ - Fetch the WorkspaceInstance + Asynchronous coroutine to fetch the WorkspaceInstance + :returns: The fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return WorkspaceInstance(self._version, payload, sid=self._solution['sid'], ) + 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=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): + 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 SID of the Activity that will be used when new Workers are created in the Workspace - :param unicode event_callback_url: The URL we should call when an event occurs - :param unicode events_filter: The list of Workspace events for which to call event_callback_url - :param unicode friendly_name: A string to describe the Workspace resource - :param bool multi_task_enabled: Whether multi-tasking is enabled - :param unicode 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 WorkspaceInstance.QueueOrder prioritize_queue_order: The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return WorkspaceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the WorkspaceInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronous coroutine to update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) @property - def activities(self): + 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) + + +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): + 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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'default_activity_name': payload.get('default_activity_name'), - 'default_activity_sid': payload.get('default_activity_sid'), - 'event_callback_url': payload.get('event_callback_url'), - 'events_filter': payload.get('events_filter'), - 'friendly_name': payload.get('friendly_name'), - 'multi_task_enabled': payload.get('multi_task_enabled'), - 'sid': payload.get('sid'), - 'timeout_activity_name': payload.get('timeout_activity_name'), - 'timeout_activity_sid': payload.get('timeout_activity_sid'), - 'prioritize_queue_order': payload.get('prioritize_queue_order'), - 'url': payload.get('url'), - 'links': payload.get('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 SID of the Account that created the resource - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + :returns: The created WorkspaceInstance """ - return self._properties['date_updated'] - @property - def default_activity_name(self): - """ - :returns: The name of the default activity - :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 SID of the Activity that will be used when new Workers are created in the Workspace - :rtype: unicode - """ - return self._properties['default_activity_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def event_callback_url(self): - """ - :returns: The URL we call when an event occurs - :rtype: unicode - """ - return self._properties['event_callback_url'] + headers["Accept"] = "application/json" - @property - def events_filter(self): - """ - :returns: The list of Workspace events for which to call event_callback_url - :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 string that you assigned to describe the Workspace resource - :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: - @property - def multi_task_enabled(self): - """ - :returns: Whether multi-tasking is enabled - :rtype: bool + :returns: The created WorkspaceInstance """ - return self._properties['multi_task_enabled'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + 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 timeout_activity_name(self): - """ - :returns: The name of the timeout activity - :rtype: unicode - """ - return self._properties['timeout_activity_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def timeout_activity_sid(self): - """ - :returns: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response - :rtype: unicode - """ - return self._properties['timeout_activity_sid'] + headers["Accept"] = "application/json" - @property - def prioritize_queue_order(self): - """ - :returns: The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues - :rtype: WorkspaceInstance.QueueOrder - """ - return self._properties['prioritize_queue_order'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def url(self): - """ - :returns: The absolute URL of the Workspace resource - :rtype: unicode - """ - return self._properties['url'] + return WorkspaceInstance(self._version, payload) - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkspaceInstance]: """ - return self._properties['links'] + 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. - def fetch(self): - """ - Fetch the WorkspaceInstance + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: The fetched WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + :returns: Generator that will yield up to limit results """ - return self._proxy.fetch() + 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"]) - 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): + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkspaceInstance]: """ - Update the WorkspaceInstance + Asynchronously streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. - :param unicode default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace - :param unicode event_callback_url: The URL we should call when an event occurs - :param unicode events_filter: The list of Workspace events for which to call event_callback_url - :param unicode friendly_name: A string to describe the Workspace resource - :param bool multi_task_enabled: Whether multi-tasking is enabled - :param unicode 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 WorkspaceInstance.QueueOrder prioritize_queue_order: The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) - :returns: The updated WorkspaceInstance - :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance + :returns: Generator that will yield up to limit results """ - 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, + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] ) - def delete(self): - """ - Deletes the WorkspaceInstance + return self._version.stream_async(page, limits["limit"]) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: """ - return self._proxy.delete() + Lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def activities(self): - """ - Access the activities + :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, + ) + ) - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: """ - return self._proxy.activities + 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. - @property - def events(self): - """ - Access the events + :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, + ) + ] - :returns: twilio.rest.taskrouter.v1.workspace.event.EventList - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventList + 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: """ - return self._proxy.events + Retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately - @property - def tasks(self): - """ - Access the tasks + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList + :returns: Page of WorkspaceInstance """ - return self._proxy.tasks + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def task_queues(self): - """ - Access the task_queues + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueList - """ - return self._proxy.task_queues + headers["Accept"] = "application/json" - @property - def workers(self): - """ - Access the workers + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) - :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerList + 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: """ - return self._proxy.workers + Asynchronously retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately - @property - def workflows(self): - """ - Access the workflows + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList + :returns: Page of WorkspaceInstance """ - return self._proxy.workflows + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def statistics(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 WorkspacePage(self._version, response) + + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList + :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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsList + :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 9b26bb7e7c..4e3e416af7 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -1,443 +1,686 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the Activity + :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 of the Activity resources to read - :param unicode available: Whether to return activities that are available or unavailable - :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']) + :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 of the Activity resources to read - :param unicode available: Whether to return activities that are available or unavailable - :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 of the Activity resources to read - :param unicode available: Whether to return activities that are available or unavailable - :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Available': available, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ActivityPage(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 + ) -> "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 the ActivityInstance + Asynchronous coroutine to update the ActivityInstance - :param unicode friendly_name: A string to describe the Activity resource - :param bool available: Whether the Worker should be eligible to receive a Task when it occupies the Activity + :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 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(method='POST', uri=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 of the resource to fetch - :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 of the resource to fetch + # 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 SID of the Workspace that contains the Activity - :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 + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> ActivityInstance: """ - Build an instance of ActivityInstance + Fetch the ActivityInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance + :returns: The fetched ActivityInstance """ - return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_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 ActivityContext(InstanceContext): - """ """ + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, workspace_sid, sid): + async def fetch_async(self) -> ActivityInstance: """ - Initialize the ActivityContext + Asynchronous coroutine to fetch the ActivityInstance - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the Activity resources to fetch - :param sid: The SID of the resource to fetch - :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext + :returns: The fetched ActivityInstance """ - super(ActivityContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'sid': sid, } - self._uri = '/Workspaces/{workspace_sid}/Activities/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the ActivityInstance + headers["Accept"] = "application/json" - :returns: The fetched ActivityInstance - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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: A string to describe the Activity resource + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ActivityInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + 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(method='DELETE', uri=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.get('account_sid'), - 'available': payload.get('available'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 SID of the Account that created the resource - :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: Whether the Worker should be eligible to receive a Task when it occupies the Activity - :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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 string that you assigned to describe the Activity resource - :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 unique string that identifies the resource - :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 SID of the Workspace that contains the Activity - :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 absolute URL of the Activity resource - :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 - def fetch(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance """ - Fetch the ActivityInstance + response = self._version.domain.twilio.request("GET", target_url) + return ActivityPage(self._version, response, self._solution) - :returns: The 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: A string to describe the Activity resource + def get(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext - :returns: The 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 708868bebf..1b7f289e5e 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -1,530 +1,658 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 of the Workspace that contains the Event + 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, task_channel=values.unset, - 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: Only include usage that occurred on or before this date - :param unicode event_type: The type of Events to read - :param unicode minutes: The period of events to read in minutes - :param unicode reservation_sid: The SID of the Reservation with the Events to read - :param datetime start_date: Only include Events from on or after this date - :param unicode task_queue_sid: The SID of the TaskQueue with the Events to read - :param unicode task_sid: The SID of the Task with the Events to read - :param unicode worker_sid: The SID of the Worker with the Events to read - :param unicode workflow_sid: The SID of the Worker with the Events to read - :param unicode task_channel: The TaskChannel with the Events to read - :param unicode sid: The unique string that identifies the resource - :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) + return self._proxy.fetch() - 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'], - ) + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance - return self._version.stream(page, limits['limit']) - 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, task_channel=values.unset, sid=values.unset, - limit=None, page_size=None): + :returns: The fetched 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. + return await self._proxy.fetch_async() - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode event_type: The type of Events to read - :param unicode minutes: The period of events to read in minutes - :param unicode reservation_sid: The SID of the Reservation with the Events to read - :param datetime start_date: Only include Events from on or after this date - :param unicode task_queue_sid: The SID of the TaskQueue with the Events to read - :param unicode task_sid: The SID of the Task with the Events to read - :param unicode worker_sid: The SID of the Worker with the Events to read - :param unicode workflow_sid: The SID of the Worker with the Events to read - :param unicode task_channel: The TaskChannel with the Events to read - :param unicode sid: The unique string that identifies the resource - :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] + def __repr__(self) -> str: """ - 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, - )) - - 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, task_channel=values.unset, sid=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + Provide a friendly representation + + :returns: Machine friendly representation """ - Retrieve a single page of EventInstance records from the API. - Request is executed immediately + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode event_type: The type of Events to read - :param unicode minutes: The period of events to read in minutes - :param unicode reservation_sid: The SID of the Reservation with the Events to read - :param datetime start_date: Only include Events from on or after this date - :param unicode task_queue_sid: The SID of the TaskQueue with the Events to read - :param unicode task_sid: The SID of the Task with the Events to read - :param unicode worker_sid: The SID of the Worker with the Events to read - :param unicode workflow_sid: The SID of the Worker with the Events to read - :param unicode task_channel: The TaskChannel with the Events to read - :param unicode sid: The unique string that identifies the resource - :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 EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) +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 of the resource to fetch + 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 of the resource to fetch + 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 + ) + + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The SID of the Workspace that contains the Event + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.taskrouter.v1.workspace.event.EventPage - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventPage + :returns: Machine friendly representation """ - super(EventPage, 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 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.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 SID of the Workspace with the Event to fetch - :param sid: The SID of the resource to fetch + :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 the 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: The fetched EventInstance - :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + :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) - return EventInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_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( + 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"], ) - def __repr__(self): - """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - 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.get('account_sid'), - 'actor_sid': payload.get('actor_sid'), - 'actor_type': payload.get('actor_type'), - 'actor_url': payload.get('actor_url'), - 'description': payload.get('description'), - 'event_data': payload.get('event_data'), - 'event_date': deserialize.iso8601_datetime(payload.get('event_date')), - 'event_date_ms': deserialize.integer(payload.get('event_date_ms')), - 'event_type': payload.get('event_type'), - 'resource_sid': payload.get('resource_sid'), - 'resource_type': payload.get('resource_type'), - 'resource_url': payload.get('resource_url'), - 'sid': payload.get('sid'), - 'source': payload.get('source'), - 'source_ip_address': payload.get('source_ip_address'), - 'url': payload.get('url'), - 'workspace_sid': payload.get('workspace_sid'), - } + :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 SID of the Account that created the resource - :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 SID of the resource that triggered the event - :rtype: unicode - """ - return self._properties['actor_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def actor_type(self): - """ - :returns: The type of resource that triggered the event - :rtype: unicode - """ - return self._properties['actor_type'] + headers["Accept"] = "application/json" - @property - def actor_url(self): - """ - :returns: The absolute URL of the resource that triggered the event - :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: A description of the event - :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: Data about the event - :rtype: dict - """ - 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 time the event was sent - :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_date_ms(self): - """ - :returns: The time the event was sent in milliseconds - :rtype: unicode - """ - return self._properties['event_date_ms'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def event_type(self): - """ - :returns: The identifier for the event - :rtype: unicode - """ - return self._properties['event_type'] + headers["Accept"] = "application/json" - @property - def resource_sid(self): - """ - :returns: The SID of the object the event is most relevant to - :rtype: unicode - """ - return self._properties['resource_sid'] + 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_type(self): - """ - :returns: The type of object the event is most relevant to - :rtype: unicode + def get_page(self, target_url: str) -> EventPage: """ - return self._properties['resource_type'] + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def resource_url(self): - """ - :returns: The URL of the resource the event is most relevant to - :rtype: unicode - """ - return self._properties['resource_url'] + :param target_url: API-generated URL for the requested results page - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['sid'] + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) - @property - def source(self): + async def get_page_async(self, target_url: str) -> EventPage: """ - :returns: Where the Event originated - :rtype: unicode - """ - return self._properties['source'] + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately - @property - def source_ip_address(self): - """ - :returns: The IP from which the Event originated - :rtype: unicode - """ - return self._properties['source_ip_address'] + :param target_url: API-generated URL for the requested results page - @property - def url(self): - """ - :returns: The absolute URL of the Event resource - :rtype: unicode + :returns: Page of EventInstance """ - return self._properties['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) - @property - def workspace_sid(self): + def get(self, sid: str) -> EventContext: """ - :returns: The SID of the Workspace that contains the Event - :rtype: unicode + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. """ - return self._properties['workspace_sid'] + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> EventContext: """ - Fetch the EventInstance + Constructs a EventContext - :returns: The 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 d97c6513a7..2c4516df77 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -1,689 +1,1050 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +class TaskInstance(InstanceResource): - def __init__(self, version, workspace_sid): - """ - Initialize the TaskList + class Status(object): + PENDING = "pending" + RESERVED = "reserved" + ASSIGNED = "assigned" + CANCELED = "canceled" + COMPLETED = "completed" + WRAPPING = "wrapping" - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Task + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task resource. + :ivar age: The number of seconds since the Task was created. + :ivar assignment_status: + :ivar attributes: The JSON string with custom attributes of the work. **Note** If this property has been assigned a value, it will only be displayed in FETCH action that returns a single resource. Otherwise, it will be null. + :ivar addons: An object that contains the [Add-on](https://www.twilio.com/docs/add-ons) data for all installed Add-ons. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar task_queue_entered_date: The date and time in GMT when the Task entered the TaskQueue, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar priority: The current priority score of the Task as assigned to a Worker by the workflow. Tasks with higher priority values will be assigned before Tasks with lower values. + :ivar reason: The reason the Task was canceled or completed, if applicable. + :ivar sid: The unique string that we created to identify the Task resource. + :ivar task_queue_sid: The SID of the TaskQueue. + :ivar task_queue_friendly_name: The friendly name of the TaskQueue. + :ivar task_channel_sid: The SID of the TaskChannel. + :ivar task_channel_unique_name: The unique name of the TaskChannel. + :ivar timeout: The amount of time in seconds that the Task can live before being assigned. + :ivar workflow_sid: The SID of the Workflow that is controlling the Task. + :ivar workflow_friendly_name: The friendly name of the Workflow that is controlling the Task. + :ivar workspace_sid: The SID of the Workspace that contains the Task. + :ivar url: The absolute URL of the Task resource. + :ivar links: The URLs of related resources. + :ivar virtual_start_time: The date and time in GMT indicating the ordering for routing of the Task specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :ivar routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.age: Optional[int] = deserialize.integer(payload.get("age")) + self.assignment_status: Optional["TaskInstance.Status"] = payload.get( + "assignment_status" + ) + self.attributes: Optional[str] = payload.get("attributes") + self.addons: Optional[str] = payload.get("addons") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.task_queue_entered_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("task_queue_entered_date") + ) + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.reason: Optional[str] = payload.get("reason") + self.sid: Optional[str] = payload.get("sid") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.task_queue_friendly_name: Optional[str] = payload.get( + "task_queue_friendly_name" + ) + self.task_channel_sid: Optional[str] = payload.get("task_channel_sid") + self.task_channel_unique_name: Optional[str] = payload.get( + "task_channel_unique_name" + ) + self.timeout: Optional[int] = deserialize.integer(payload.get("timeout")) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workflow_friendly_name: Optional[str] = payload.get( + "workflow_friendly_name" + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.virtual_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("virtual_start_time") + ) + self.ignore_capacity: Optional[bool] = payload.get("ignore_capacity") + self.routing_target: Optional[str] = payload.get("routing_target") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskContext] = None - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskList - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskList + @property + def _proxy(self) -> "TaskContext": """ - super(TaskList, 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, } - self._uri = '/Workspaces/{workspace_sid}/Tasks'.format(**self._solution) + :returns: TaskContext for this TaskInstance + """ + if self._context is None: + self._context = TaskContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context - def 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): + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - 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. + Deletes the TaskInstance - :param unicode priority: The priority value of the Tasks to read - :param unicode assignment_status: Returns the list of all Tasks in the Workspace with the specified assignment_status - :param unicode workflow_sid: The SID of the Workflow with the Tasks to read - :param unicode workflow_name: The friendly name of the Workflow with the Tasks to read - :param unicode task_queue_sid: The SID of the TaskQueue with the Tasks to read - :param unicode task_queue_name: The friendly_name of the TaskQueue with the Tasks to read - :param unicode evaluate_task_attributes: The task attributes of the Tasks to read - :param unicode ordering: Controls the order of the Tasks returned - :param bool has_addons: Whether to read Tasks with 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) + :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.TaskInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - ordering=ordering, - has_addons=has_addons, - page_size=limits['page_size'], + return self._proxy.delete( + if_match=if_match, ) - return self._version.stream(page, limits['limit']) - - 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): + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Lists TaskInstance 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 TaskInstance - :param unicode priority: The priority value of the Tasks to read - :param unicode assignment_status: Returns the list of all Tasks in the Workspace with the specified assignment_status - :param unicode workflow_sid: The SID of the Workflow with the Tasks to read - :param unicode workflow_name: The friendly name of the Workflow with the Tasks to read - :param unicode task_queue_sid: The SID of the TaskQueue with the Tasks to read - :param unicode task_queue_name: The friendly_name of the TaskQueue with the Tasks to read - :param unicode evaluate_task_attributes: The task attributes of the Tasks to read - :param unicode ordering: Controls the order of the Tasks returned - :param bool has_addons: Whether to read Tasks with 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) + :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: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.task.TaskInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - )) + return await self._proxy.delete_async( + if_match=if_match, + ) - 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 fetch(self) -> "TaskInstance": """ - Retrieve a single page of TaskInstance records from the API. - Request is executed immediately - - :param unicode priority: The priority value of the Tasks to read - :param unicode assignment_status: Returns the list of all Tasks in the Workspace with the specified assignment_status - :param unicode workflow_sid: The SID of the Workflow with the Tasks to read - :param unicode workflow_name: The friendly name of the Workflow with the Tasks to read - :param unicode task_queue_sid: The SID of the TaskQueue with the Tasks to read - :param unicode task_queue_name: The friendly_name of the TaskQueue with the Tasks to read - :param unicode evaluate_task_attributes: The task attributes of the Tasks to read - :param unicode ordering: Controls the order of the Tasks returned - :param bool has_addons: Whether to read Tasks with 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 - - :returns: Page of TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage - """ - 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, - 'Ordering': ordering, - 'HasAddons': has_addons, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + Fetch the TaskInstance - return TaskPage(self._version, response, self._solution) - def get_page(self, target_url): + :returns: The fetched TaskInstance """ - Retrieve a specific page of TaskInstance 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 TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskPage + async def fetch_async(self) -> "TaskInstance": """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + Asynchronous coroutine to fetch the TaskInstance - 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): + :returns: The fetched TaskInstance """ - Create the TaskInstance - - :param unicode timeout: The amount of time in seconds the task is allowed to live - :param unicode priority: The priority to assign the new task and override the default - :param unicode task_channel: When MultiTasking is enabled specify the TaskChannel by passing either its unique_name or SID - :param unicode workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task - :param unicode attributes: A URL-encoded JSON string describing the attributes of the task + return await self._proxy.fetch_async() - :returns: The created TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + 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": """ - data = values.of({ - 'Timeout': timeout, - 'Priority': priority, - 'TaskChannel': task_channel, - 'WorkflowSid': workflow_sid, - 'Attributes': attributes, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Update the TaskInstance - return TaskInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :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 get(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 of the resource to fetch + 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: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + :returns: The updated TaskInstance """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + 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, + ) - def __call__(self, sid): + @property + def reservations(self) -> ReservationList: """ - Constructs a TaskContext - - :param sid: The SID of the resource to fetch - - :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext + Access the reservations """ - return TaskContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + 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 SID of the Workspace that contains the Task + 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 SID of the Workspace with the Task to fetch - :param sid: The SID of the resource to fetch - :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" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - # Dependents - self._reservations = None + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> TaskInstance: """ - Fetch the TaskInstance + Asynchronous coroutine to fetch the TaskInstance + :returns: The fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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 JSON string that describes the custom attributes of the task - :param TaskInstance.Status assignment_status: The new status of the task - :param unicode reason: The reason that the Task was canceled or complete - :param unicode priority: The Task's new priority value - :param unicode task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance """ - data = values.of({ - 'Attributes': attributes, - 'AssignmentStatus': assignment_status, - 'Reason': reason, - 'Priority': priority, - 'TaskChannel': task_channel, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return TaskInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated TaskInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) @property - def reservations(self): + 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.get('account_sid'), - 'age': deserialize.integer(payload.get('age')), - 'assignment_status': payload.get('assignment_status'), - 'attributes': payload.get('attributes'), - 'addons': payload.get('addons'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'task_queue_entered_date': deserialize.iso8601_datetime(payload.get('task_queue_entered_date')), - 'priority': deserialize.integer(payload.get('priority')), - 'reason': payload.get('reason'), - 'sid': payload.get('sid'), - 'task_queue_sid': payload.get('task_queue_sid'), - 'task_queue_friendly_name': payload.get('task_queue_friendly_name'), - 'task_channel_sid': payload.get('task_channel_sid'), - 'task_channel_unique_name': payload.get('task_channel_unique_name'), - 'timeout': deserialize.integer(payload.get('timeout')), - 'workflow_sid': payload.get('workflow_sid'), - 'workflow_friendly_name': payload.get('workflow_friendly_name'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def age(self): - """ - :returns: The number of seconds since the Task was created - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['age'] + return "" - @property - def assignment_status(self): - """ - :returns: The current status of the Task's assignment - :rtype: TaskInstance.Status - """ - return self._properties['assignment_status'] - @property - def attributes(self): - """ - :returns: The JSON string with custom attributes of the work - :rtype: unicode - """ - return self._properties['attributes'] +class TaskList(ListResource): - @property - def addons(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: An object that contains the addon data for all installed addons - :rtype: unicode - """ - return self._properties['addons'] + Initialize the TaskList - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + super().__init__(version) - @property - def task_queue_entered_date(self): - """ - :returns: The ISO 8601 date and time in GMT when the Task entered the TaskQueue. - :rtype: datetime + # 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: """ - return self._properties['task_queue_entered_date'] + Create the TaskInstance - @property - def priority(self): - """ - :returns: Retrieve the list of all Tasks in the Workspace with the specified priority - :rtype: unicode - """ - return self._properties['priority'] + :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 - @property - def reason(self): - """ - :returns: The reason the Task was canceled or completed - :rtype: unicode + :returns: The created TaskInstance """ - return self._properties['reason'] - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + 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_queue_sid(self): - """ - :returns: The SID of the TaskQueue - :rtype: unicode - """ - return self._properties['task_queue_sid'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def task_queue_friendly_name(self): - """ - :returns: The friendly name of the TaskQueue - :rtype: unicode - """ - return self._properties['task_queue_friendly_name'] + headers["Accept"] = "application/json" - @property - def task_channel_sid(self): - """ - :returns: The SID of the TaskChannel - :rtype: unicode - """ - return self._properties['task_channel_sid'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def task_channel_unique_name(self): - """ - :returns: The unique name of the TaskChannel - :rtype: unicode - """ - return self._properties['task_channel_unique_name'] + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def timeout(self): - """ - :returns: The amount of time in seconds that the Task is allowed to live - :rtype: unicode - """ - return self._properties['timeout'] + 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 - @property - def workflow_sid(self): - """ - :returns: The SID of the Workflow that is controlling the Task - :rtype: unicode + :returns: The created TaskInstance """ - return self._properties['workflow_sid'] - @property - def workflow_friendly_name(self): - """ - :returns: The friendly name of the Workflow that is controlling the Task - :rtype: unicode + data = values.of( + { + "Timeout": timeout, + "Priority": priority, + "TaskChannel": task_channel, + "WorkflowSid": workflow_sid, + "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: """ - 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 SID of the Workspace that contains the Task - :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 absolute URL of the Task resource - :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 URLs of related resources - :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, + } + ) + + 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 TaskPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskPage: """ - Fetch the TaskInstance + Retrieve a specific page of TaskInstance records from the API. + Request is executed immediately - :returns: The fetched TaskInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance + :param target_url: API-generated URL for the requested results page + + :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 JSON string that describes the custom attributes of the task - :param TaskInstance.Status assignment_status: The new status of the task - :param unicode reason: The reason that the Task was canceled or complete - :param unicode priority: The Task's new priority value - :param unicode task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update + :param target_url: API-generated URL for the requested results page - :returns: The 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 7062198881..28cb03339a 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -1,758 +1,1351 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that this task is contained within. - :param task_sid: The SID of the reserved Task resource - - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationList - """ - super(ReservationList, self).__init__(version) +class ReservationInstance(InstanceResource): - # 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 CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" - 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 ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" - :param ReservationInstance.Status reservation_status: Returns the list of reservations for a task with a specified ReservationStatus - :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): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" - :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 SupervisorMode(object): + MONITOR = "monitor" + WHISPER = "whisper" + BARGE = "barge" - 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 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']) + 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: Returns the list of reservations for a task with a specified ReservationStatus - :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: Returns the list of reservations for a task with a specified ReservationStatus - :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 """ - data = values.of({ - 'ReservationStatus': reservation_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 + Update the ReservationInstance - :param sid: The SID of the TaskReservation resource to fetch + :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: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + :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 of the TaskReservation resource to fetch + 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: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + :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 SID of the Workspace that this task is contained within. - :param task_sid: The SID of the reserved Task resource + 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 + ) - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the TaskReservation resource to fetch - :param task_sid: The SID of the reserved Task resource with the TaskReservation resource to fetch - :param sid: The SID of the TaskReservation resource to fetch + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext + 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: """ - super(ReservationContext, self).__init__(version) + Update the ReservationInstance - # 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) + :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`. - def fetch(self): + :returns: The updated ReservationInstance """ - Fetch the ReservationInstance - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ReservationInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], + 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, supervisor_mode=values.unset, - supervisor=values.unset, - end_conference_on_customer_exit=values.unset, - beep_on_customer_entrance=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: """ - Update the ReservationInstance - - :param ReservationInstance.Status reservation_status: The new status of the reservation - :param unicode worker_activity_sid: The new worker activity SID if rejecting a reservation - :param unicode instruction: The assignment instruction for reservation - :param unicode dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction - :param unicode dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction - :param unicode dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction - :param unicode dequeue_timeout: Timeout for call when executing a Dequeue instruction - :param unicode dequeue_to: The Contact URI of the worker when executing a Dequeue instruction - :param unicode dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction - :param unicode call_from: The Caller ID of the outbound call when executing a Call instruction - :param unicode call_record: Whether to record both legs of a call when executing a Call instruction - :param unicode call_timeout: Timeout for call when executing a Call instruction - :param unicode call_to: The Contact URI of the worker when executing a Call instruction - :param unicode call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction - :param unicode call_status_callback_url: The URL to call for the completed call event when executing a Call instruction - :param bool call_accept: Whether to accept a reservation when executing a Call instruction - :param unicode redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction - :param bool redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction - :param unicode redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction - :param unicode to: The Contact URI of the worker when executing a Conference instruction - :param unicode from_: The Caller ID of the call to the worker when executing a Conference instruction - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param ReservationInstance.CallStatus status_callback_event: The call progress events that we will send to status_callback - :param unicode timeout: Timeout for call when executing a Conference instruction - :param bool record: Whether to record the participant and their conferences - :param bool muted: Whether to mute the agent - :param unicode beep: Whether to play a notification beep when the participant joins - :param bool start_conference_on_enter: Whether the conference starts when the participant joins the conference - :param bool end_conference_on_exit: Whether to end the conference when the agent leaves - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool early_media: Whether agents can hear the state of the outbound call - :param unicode max_participants: The maximum number of agent conference participants - :param unicode conference_status_callback: The callback URL for conference events - :param unicode conference_status_callback_method: HTTP method for requesting `conference_status_callback` URL - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference status events that we will send to conference_status_callback - :param unicode conference_record: Whether to record the conference the participant is joining - :param unicode conference_trim: How to trim leading and trailing silence from your recorded conference audio files - :param unicode recording_channels: Specify `mono` or `dual` recording channels - :param unicode recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes - :param unicode recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback` - :param unicode conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available - :param unicode conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback` - :param unicode region: The region where we should mix the conference audio - :param unicode sip_auth_username: The SIP username used for authentication - :param unicode sip_auth_password: The SIP password for authentication - :param unicode dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction - :param unicode post_work_activity_sid: The new worker activity SID after executing a Conference instruction - :param ReservationInstance.SupervisorMode supervisor_mode: The Supervisor mode when executing the Supervise instruction - :param unicode supervisor: The Supervisor SID/URI when executing the Supervise instruction - :param bool end_conference_on_customer_exit: Whether to end the conference when the customer leaves - :param bool beep_on_customer_entrance: Whether to play a notification beep when the customer joins + 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 - :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, - 'SupervisorMode': supervisor_mode, - 'Supervisor': supervisor, - 'EndConferenceOnCustomerExit': end_conference_on_customer_exit, - 'BeepOnCustomerEntrance': beep_on_customer_entrance, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return ReservationInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - task_sid=self._solution['task_sid'], - sid=self._solution['sid'], + 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 Status(object): - PENDING = "pending" - ACCEPTED = "accepted" - REJECTED = "rejected" - TIMEOUT = "timeout" - CANCELED = "canceled" - RESCINDED = "rescinded" - WRAPPING = "wrapping" - COMPLETED = "completed" +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"], + task_sid=self._solution["task_sid"], + ) - class SupervisorMode(object): - MONITOR = "monitor" - WHISPER = "whisper" - BARGE = "barge" + 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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'reservation_status': payload.get('reservation_status'), - 'sid': payload.get('sid'), - 'task_sid': payload.get('task_sid'), - 'worker_name': payload.get('worker_name'), - 'worker_sid': payload.get('worker_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - 'links': payload.get('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. + + """ + super().__init__(version) - # Context - self._context = None + # 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 SID of the Account that created the resource - :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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream(page, limits["limit"]) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + 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]: """ - 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 current status of the reservation - :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: The unique string that identifies the resource - :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( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) - @property - def task_sid(self): - """ - :returns: The SID of the reserved Task resource - :rtype: unicode + 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['task_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 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 friendly_name of the Worker that is reserved - :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['worker_name'] + 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_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 SID of the reserved Worker resource - :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_sid'] + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): + :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 """ - :returns: The SID of the Workspace that this task is contained within. - :rtype: unicode + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: """ - return self._properties['workspace_sid'] + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the TaskReservation reservation - :rtype: unicode + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: """ - return self._properties['url'] + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately - @property - def links(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance """ - :returns: The URLs of related resources - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: """ - return self._properties['links'] + 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 - def fetch(self): + :returns: Page of ReservationInstance """ - Fetch the ReservationInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance + def get(self, sid: str) -> ReservationContext: """ - return self._proxy.fetch() + Constructs a ReservationContext - 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, supervisor_mode=values.unset, - supervisor=values.unset, - end_conference_on_customer_exit=values.unset, - beep_on_customer_entrance=values.unset): + :param sid: The SID of the TaskReservation resource to update. """ - Update the ReservationInstance + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) - :param ReservationInstance.Status reservation_status: The new status of the reservation - :param unicode worker_activity_sid: The new worker activity SID if rejecting a reservation - :param unicode instruction: The assignment instruction for reservation - :param unicode dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction - :param unicode dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction - :param unicode dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction - :param unicode dequeue_timeout: Timeout for call when executing a Dequeue instruction - :param unicode dequeue_to: The Contact URI of the worker when executing a Dequeue instruction - :param unicode dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction - :param unicode call_from: The Caller ID of the outbound call when executing a Call instruction - :param unicode call_record: Whether to record both legs of a call when executing a Call instruction - :param unicode call_timeout: Timeout for call when executing a Call instruction - :param unicode call_to: The Contact URI of the worker when executing a Call instruction - :param unicode call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction - :param unicode call_status_callback_url: The URL to call for the completed call event when executing a Call instruction - :param bool call_accept: Whether to accept a reservation when executing a Call instruction - :param unicode redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction - :param bool redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction - :param unicode redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction - :param unicode to: The Contact URI of the worker when executing a Conference instruction - :param unicode from_: The Caller ID of the call to the worker when executing a Conference instruction - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param ReservationInstance.CallStatus status_callback_event: The call progress events that we will send to status_callback - :param unicode timeout: Timeout for call when executing a Conference instruction - :param bool record: Whether to record the participant and their conferences - :param bool muted: Whether to mute the agent - :param unicode beep: Whether to play a notification beep when the participant joins - :param bool start_conference_on_enter: Whether the conference starts when the participant joins the conference - :param bool end_conference_on_exit: Whether to end the conference when the agent leaves - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool early_media: Whether agents can hear the state of the outbound call - :param unicode max_participants: The maximum number of agent conference participants - :param unicode conference_status_callback: The callback URL for conference events - :param unicode conference_status_callback_method: HTTP method for requesting `conference_status_callback` URL - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference status events that we will send to conference_status_callback - :param unicode conference_record: Whether to record the conference the participant is joining - :param unicode conference_trim: How to trim leading and trailing silence from your recorded conference audio files - :param unicode recording_channels: Specify `mono` or `dual` recording channels - :param unicode recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes - :param unicode recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback` - :param unicode conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available - :param unicode conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback` - :param unicode region: The region where we should mix the conference audio - :param unicode sip_auth_username: The SIP username used for authentication - :param unicode sip_auth_password: The SIP password for authentication - :param unicode dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction - :param unicode post_work_activity_sid: The new worker activity SID after executing a Conference instruction - :param ReservationInstance.SupervisorMode supervisor_mode: The Supervisor mode when executing the Supervise instruction - :param unicode supervisor: The Supervisor SID/URI when executing the Supervise instruction - :param bool end_conference_on_customer_exit: Whether to end the conference when the customer leaves - :param bool beep_on_customer_entrance: Whether to play a notification beep when the customer joins + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext - :returns: The 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, - supervisor_mode=supervisor_mode, - supervisor=supervisor, - end_conference_on_customer_exit=end_conference_on_customer_exit, - beep_on_customer_entrance=beep_on_customer_entrance, + 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 c19e49b619..3a4b0a6b9e 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -1,457 +1,684 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the TaskChannel + :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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return TaskChannelPage(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, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": """ - Retrieve a specific page of TaskChannelInstance records from the API. - Request is executed immediately + Update the TaskChannelInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelPage + :returns: The updated TaskChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, ) - return TaskChannelPage(self._version, response, self._solution) - - def create(self, friendly_name, unique_name, - channel_optimized_routing=values.unset): + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": """ - Create the TaskChannelInstance + Asynchronous coroutine to update the TaskChannelInstance - :param unicode friendly_name: A string to describe the TaskChannel resource - :param unicode unique_name: An application-defined string that uniquely identifies the TaskChannel - :param bool channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle + :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 created TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :returns: The updated TaskChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'UniqueName': unique_name, - 'ChannelOptimizedRouting': channel_optimized_routing, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) - return TaskChannelInstance(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 TaskChannelContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The SID of the TaskChannel resource to fetch +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 of the TaskChannel resource to fetch + # 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 SID of the Workspace that contains the TaskChannel - :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): - """ - 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 TaskChannelContext(InstanceContext): - """ """ + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, workspace_sid, sid): + async def fetch_async(self) -> TaskChannelInstance: """ - Initialize the TaskChannelContext + Asynchronous coroutine to fetch the TaskChannelInstance - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the TaskChannel to fetch - :param sid: The SID of the TaskChannel resource to fetch - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + :returns: The fetched 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) + headers = values.of({}) - def fetch(self): - """ - Fetch the TaskChannelInstance + headers["Accept"] = "application/json" - :returns: The fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def update(self, friendly_name=values.unset, - channel_optimized_routing=values.unset): + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: """ Update the TaskChannelInstance - :param unicode friendly_name: A string to describe the TaskChannel resource - :param bool channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'ChannelOptimizedRouting': channel_optimized_routing, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return TaskChannelInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + 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, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: """ - Deletes the TaskChannelInstance + Asynchronous coroutine to update the TaskChannelInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 __init__(self, version, payload, workspace_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: """ - Initialize the TaskChannelInstance + Build an instance of TaskChannelInstance - :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :param payload: Payload response from the API """ - super(TaskChannelInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'unique_name': payload.get('unique_name'), - 'workspace_sid': payload.get('workspace_sid'), - 'channel_optimized_routing': payload.get('channel_optimized_routing'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_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: TaskChannelContext for this TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = TaskChannelContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + +class TaskChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['account_sid'] + Initialize the TaskChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to read. - @property - def date_created(self): """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) + + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: """ - return self._properties['date_created'] + Create the TaskChannelInstance - @property - def date_updated(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 """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + + 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: """ - return self._properties['date_updated'] + Asynchronously create the TaskChannelInstance - @property - def friendly_name(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 """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + + 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]: """ - return self._properties['friendly_name'] + 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. - @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 unique string that identifies the resource - :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[TaskChannelInstance]: """ - return self._properties['sid'] + 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. - @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: An application-defined string that uniquely identifies the TaskChannel - :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[TaskChannelInstance]: """ - return self._properties['unique_name'] + 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 workspace_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 SID of the Workspace that contains the TaskChannel - :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[TaskChannelInstance]: """ - return self._properties['workspace_sid'] + 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 channel_optimized_routing(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: Whether the TaskChannel will prioritize Workers that have been idle - :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, + ) -> TaskChannelPage: """ - return self._properties['channel_optimized_routing'] + Retrieve a single page of TaskChannelInstance 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 TaskChannelInstance """ - :returns: The absolute URL of the TaskChannel 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 = 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['url'] + Asynchronously retrieve a single page of TaskChannelInstance 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 TaskChannelInstance """ - :returns: The URLs of related resources - :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['links'] + Retrieve a specific page of TaskChannelInstance 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 TaskChannelInstance """ - Fetch the TaskChannelInstance + response = self._version.domain.twilio.request("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) - :returns: The fetched TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + async def get_page_async(self, target_url: str) -> TaskChannelPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page - def update(self, friendly_name=values.unset, - channel_optimized_routing=values.unset): + :returns: Page of TaskChannelInstance """ - Update the TaskChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) - :param unicode friendly_name: A string to describe the TaskChannel resource - :param bool channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle + def get(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext - :returns: The updated TaskChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance + :param sid: The SID of the Task Channel resource to update. """ - return self._proxy.update( - friendly_name=friendly_name, - channel_optimized_routing=channel_optimized_routing, + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid ) - def delete(self): + def __call__(self, sid: str) -> TaskChannelContext: """ - Deletes the TaskChannelInstance + Constructs a TaskChannelContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Task Channel resource to update. """ - return self._proxy.delete() + 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 1846b3a92d..4511a55310 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -1,672 +1,949 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 - +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_bulk_real_time_statistics import ( + TaskQueueBulkRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics import ( + TaskQueueCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics import ( + TaskQueueRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics import ( + TaskQueueStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics import ( + TaskQueuesStatisticsList, +) -class TaskQueueList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the TaskQueueList - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the TaskQueue +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 of the TaskQueue resources to read - :param unicode evaluate_worker_attributes: The attributes of the Workers to read - :param unicode worker_sid: The SID of the Worker with the TaskQueue resources to read - :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']) + :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 of the TaskQueue resources to read - :param unicode evaluate_worker_attributes: The attributes of the Workers to read - :param unicode worker_sid: The SID of the Worker with the TaskQueue resources to read - :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 of the TaskQueue resources to read - :param unicode evaluate_worker_attributes: The attributes of the Workers to read - :param unicode worker_sid: The SID of the Worker with the TaskQueue resources to read - :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EvaluateWorkerAttributes': evaluate_worker_attributes, - 'WorkerSid': worker_sid, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return TaskQueuePage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "TaskQueueInstance": """ - Retrieve a specific page of TaskQueueInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the TaskQueueInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage + :returns: The fetched TaskQueueInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) + return await self._proxy.fetch_async() - return TaskQueuePage(self._version, response, self._solution) - - def create(self, friendly_name, target_workers=values.unset, - max_reserved_workers=values.unset, task_order=values.unset, - reservation_activity_sid=values.unset, - assignment_activity_sid=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": """ - Create the TaskQueueInstance + Update the TaskQueueInstance - :param unicode friendly_name: A string to describe the resource - :param unicode target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue - :param unicode max_reserved_workers: The maximum number of Workers to reserve - :param TaskQueueInstance.TaskOrder task_order: How Tasks will be assigned to Workers - :param unicode reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them - :param unicode assignment_activity_sid: The SID of the Activity to assign Workers once a task is assigned to them + :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 created TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :returns: The updated 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, - }) + 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, + ) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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: - return TaskQueueInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + :returns: The updated TaskQueueInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) @property - def 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 of the resource to - - :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 of the resource to - - :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 SID of the Workspace that contains the TaskQueue + 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 SID of the Workspace with the TaskQueue to fetch - :param sid: The SID of the resource to - :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) - def fetch(self): + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskQueueInstance: """ - Fetch the TaskQueueInstance + Asynchronous coroutine to fetch the TaskQueueInstance + :returns: The fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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: A string to describe the resource - :param unicode target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue - :param unicode reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them - :param unicode assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them - :param unicode max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue - :param TaskQueueInstance.TaskOrder task_order: How Tasks will be assigned to Workers + :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 - :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, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return TaskQueueInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated TaskQueueInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) @property - def 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) - - -class TaskQueueInstance(InstanceResource): - """ """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - 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.get('account_sid'), - 'assignment_activity_sid': payload.get('assignment_activity_sid'), - 'assignment_activity_name': payload.get('assignment_activity_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'max_reserved_workers': deserialize.integer(payload.get('max_reserved_workers')), - 'reservation_activity_sid': payload.get('reservation_activity_sid'), - 'reservation_activity_name': payload.get('reservation_activity_name'), - 'sid': payload.get('sid'), - 'target_workers': payload.get('target_workers'), - 'task_order': payload.get('task_order'), - 'url': payload.get('url'), - 'workspace_sid': payload.get('workspace_sid'), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assignment_activity_sid(self): - """ - :returns: The SID of the Activity to assign Workers when a task is assigned for them - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assignment_activity_sid'] + return "" - @property - def assignment_activity_name(self): - """ - :returns: The name of the Activity to assign Workers when a task is assigned for them - :rtype: unicode - """ - return self._properties['assignment_activity_name'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class TaskQueueList(ListResource): - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 string that you assigned to describe the resource - :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 maximum number of Workers to reserve - :rtype: unicode """ - return self._properties['max_reserved_workers'] + super().__init__(version) - @property - def reservation_activity_sid(self): - """ - :returns: The SID of the Activity to assign Workers once a task is reserved for them - :rtype: unicode + # 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: """ - return self._properties['reservation_activity_sid'] + Create the TaskQueueInstance - @property - def reservation_activity_name(self): - """ - :returns: The name of the Activity to assign Workers once a task is reserved for them - :rtype: unicode - """ - return self._properties['reservation_activity_name'] + :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. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: The created TaskQueueInstance """ - return self._properties['sid'] - @property - def target_workers(self): - """ - :returns: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue - :rtype: unicode + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronously create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance """ - return self._properties['target_workers'] - @property - def task_order(self): + 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: How Tasks will be assigned to Workers - :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 absolute URL of the TaskQueue resource - :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 SID of the Workspace that contains the TaskQueue - :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 URLs of related resources - :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 the TaskQueueInstance + Retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately - :returns: The fetched TaskQueueInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance + :param target_url: API-generated URL for the requested results page + + :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: A string to describe the resource - :param unicode target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue - :param unicode reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them - :param unicode assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them - :param unicode max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue - :param TaskQueueInstance.TaskOrder task_order: How Tasks will be assigned to Workers + :param target_url: API-generated URL for the requested results page - :returns: The 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 f789d0b65a..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,448 +1,376 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated - - :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, } +from twilio.base.version import Version - 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 SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated + :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 SID of the Workspace with the TaskQueue to fetch - :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics - - :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): + 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 datetime end_date: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - return TaskQueueCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + 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, + } ) - 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.get('account_sid'), - 'avg_task_acceptance_time': deserialize.integer(payload.get('avg_task_acceptance_time')), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'reservations_created': deserialize.integer(payload.get('reservations_created')), - 'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')), - 'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')), - 'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')), - 'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')), - 'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')), - 'split_by_wait_time': payload.get('split_by_wait_time'), - 'task_queue_sid': payload.get('task_queue_sid'), - 'wait_duration_until_accepted': payload.get('wait_duration_until_accepted'), - 'wait_duration_until_canceled': payload.get('wait_duration_until_canceled'), - 'wait_duration_in_queue_until_accepted': payload.get('wait_duration_in_queue_until_accepted'), - 'tasks_canceled': deserialize.integer(payload.get('tasks_canceled')), - 'tasks_completed': deserialize.integer(payload.get('tasks_completed')), - 'tasks_deleted': deserialize.integer(payload.get('tasks_deleted')), - 'tasks_entered': deserialize.integer(payload.get('tasks_entered')), - 'tasks_moved': deserialize.integer(payload.get('tasks_moved')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 + headers = values.of({}) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def avg_task_acceptance_time(self): - """ - :returns: The average time in seconds between Task creation and acceptance - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def start_time(self): - """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def end_time(self): + 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: """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['end_time'] + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance - @property - def reservations_created(self): - """ - :returns: The total number of Reservations created for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_created'] + :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. - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted for Tasks in the TaskQueue - :rtype: unicode + :returns: The fetched TaskQueueCumulativeStatisticsInstance """ - return self._properties['reservations_accepted'] - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations rejected for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_rejected'] + 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 total number of Reservations that timed out for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers = values.of({}) - @property - def reservations_canceled(self): - """ - :returns: The total number of Reservations canceled for Tasks in the TaskQueue - :rtype: unicode - """ - return self._properties['reservations_canceled'] - - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + headers["Accept"] = "application/json" - @property - def split_by_wait_time(self): - """ - :returns: A list of objects that describe the Tasks canceled and reservations accepted above and below the specified thresholds - :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 task_queue_sid(self): - """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode - """ - return self._properties['task_queue_sid'] + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def wait_duration_until_accepted(self): - """ - :returns: The wait duration statistics for Tasks accepted while in the TaskQueue - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['wait_duration_until_accepted'] + Provide a friendly representation - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait duration statistics for Tasks canceled while in the TaskQueue - :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 wait_duration_in_queue_until_accepted(self): - """ - :returns: The relative wait duration statistics for Tasks accepted while in the TaskQueue - :rtype: dict - """ - return self._properties['wait_duration_in_queue_until_accepted'] - @property - def tasks_canceled(self): - """ - :returns: The total number of Tasks canceled in the TaskQueue - :rtype: unicode - """ - return self._properties['tasks_canceled'] +class TaskQueueCumulativeStatisticsList(ListResource): - @property - def tasks_completed(self): - """ - :returns: The total number of Tasks completed in the TaskQueue - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - return self._properties['tasks_completed'] + Initialize the TaskQueueCumulativeStatisticsList - @property - def tasks_deleted(self): - """ - :returns: The total number of Tasks deleted in the TaskQueue - :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 total number of Tasks entered into the TaskQueue - :rtype: unicode """ - return self._properties['tasks_entered'] + super().__init__(version) - @property - def tasks_moved(self): - """ - :returns: The total number of Tasks that were moved from one queue to another - :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 SID of the Workspace that contains the TaskQueue - :rtype: unicode + def get(self) -> TaskQueueCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a TaskQueueCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the TaskQueue statistics resource - :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 the TaskQueueCumulativeStatisticsInstance - - :param datetime end_date: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a TaskQueueCumulativeStatisticsContext - :returns: The 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 c4f10d73c0..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,351 +1,291 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueRealTimeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated - - :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 SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated + :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 SID of the Workspace with the TaskQueue to fetch - :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics - - :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 the TaskQueueRealTimeStatisticsInstance - :param unicode task_channel: The TaskChannel for which to fetch statistics + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :returns: The fetched TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance """ - data = values.of({'TaskChannel': task_channel, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - - return TaskQueueRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + data = values.of( + { + "TaskChannel": task_channel, + } ) - 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) + headers = values.of({}) + headers["Accept"] = "application/json" -class TaskQueueRealTimeStatisticsInstance(InstanceResource): - """ """ + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - def __init__(self, version, payload, workspace_sid, task_queue_sid): - """ - Initialize the TaskQueueRealTimeStatisticsInstance + return TaskQueueRealTimeStatisticsInstance( + 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_real_time_statistics.TaskQueueRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: """ - super(TaskQueueRealTimeStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'activity_statistics': payload.get('activity_statistics'), - 'longest_task_waiting_age': deserialize.integer(payload.get('longest_task_waiting_age')), - 'longest_task_waiting_sid': payload.get('longest_task_waiting_sid'), - 'longest_relative_task_age_in_queue': deserialize.integer(payload.get('longest_relative_task_age_in_queue')), - 'longest_relative_task_sid_in_queue': payload.get('longest_relative_task_sid_in_queue'), - 'task_queue_sid': payload.get('task_queue_sid'), - 'tasks_by_priority': payload.get('tasks_by_priority'), - 'tasks_by_status': payload.get('tasks_by_status'), - 'total_available_workers': deserialize.integer(payload.get('total_available_workers')), - 'total_eligible_workers': deserialize.integer(payload.get('total_eligible_workers')), - 'total_tasks': deserialize.integer(payload.get('total_tasks')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - } + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': 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`. - @property - def _proxy(self): + :returns: The fetched TaskQueueRealTimeStatisticsInstance """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance - :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 + data = values.of( + { + "TaskChannel": task_channel, + } + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers = values.of({}) - @property - def activity_statistics(self): - """ - :returns: The number of current Workers by Activity - :rtype: dict - """ - return self._properties['activity_statistics'] + headers["Accept"] = "application/json" - @property - def longest_task_waiting_age(self): - """ - :returns: The age of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def longest_task_waiting_sid(self): - """ - :returns: The SID of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_sid'] + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - @property - def longest_relative_task_age_in_queue(self): + def __repr__(self) -> str: """ - :returns: The relative age in the TaskQueue for the longest waiting Task. - :rtype: unicode - """ - return self._properties['longest_relative_task_age_in_queue'] + Provide a friendly representation - @property - def longest_relative_task_sid_in_queue(self): - """ - :returns: The SID of the Task waiting in the TaskQueue the longest. - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['longest_relative_task_sid_in_queue'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) - @property - def task_queue_sid(self): - """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode - """ - return self._properties['task_queue_sid'] - @property - def tasks_by_priority(self): - """ - :returns: The number of Tasks by priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] +class TaskQueueRealTimeStatisticsList(ListResource): - @property - def tasks_by_status(self): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - :returns: The number of Tasks by their current status - :rtype: dict - """ - return self._properties['tasks_by_status'] + Initialize the TaskQueueRealTimeStatisticsList - @property - def total_available_workers(self): - """ - :returns: The total number of Workers available for Tasks in the TaskQueue - :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 number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state - :rtype: unicode """ - return self._properties['total_eligible_workers'] + super().__init__(version) - @property - def total_tasks(self): - """ - :returns: The total number of 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): - """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode + def get(self) -> TaskQueueRealTimeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a TaskQueueRealTimeStatisticsContext - @property - def url(self): """ - :returns: The absolute URL of the TaskQueue statistics resource - :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 the TaskQueueRealTimeStatisticsInstance - - :param unicode task_channel: The TaskChannel for which to fetch statistics + Constructs a TaskQueueRealTimeStatisticsContext - :returns: The 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 1f0b41fcd9..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,303 +1,306 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 TaskQueueStatisticsList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid, task_queue_sid): + @property + def _proxy(self) -> "TaskQueueStatisticsContext": """ - Initialize the TaskQueueStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated + 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.task_queue.task_queue_statistics.TaskQueueStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList + :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance """ - super(TaskQueueStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } + if self._context is None: + self._context = TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context - def get(self): + 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": """ - Constructs a TaskQueueStatisticsContext + 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: 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 __call__(self): + 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": """ - Constructs a TaskQueueStatisticsContext + 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: 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 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 TaskQueueStatisticsPage(Page): - """ """ +class TaskQueueStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - Initialize the TaskQueueStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The SID of the Workspace that contains the TaskQueue - :param task_queue_sid: The SID of the TaskQueue from which these statistics were calculated + Initialize the TaskQueueStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsPage + :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(TaskQueueStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = 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 get_instance(self, payload): + 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: """ - Build an instance of TaskQueueStatisticsInstance + 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'], + + 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, + } ) - 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 TaskQueueStatisticsContext(InstanceContext): - """ """ + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) - def __init__(self, version, workspace_sid, task_queue_sid): + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: """ - Initialize the TaskQueueStatisticsContext + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance - :param Version 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 + :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 """ - super(TaskQueueStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'task_queue_sid': task_queue_sid, } - self._uri = '/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/Statistics'.format(**self._solution) - def fetch(self, end_date=values.unset, minutes=values.unset, - start_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch the 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: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + headers = values.of({}) - :returns: The fetched TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - """ - data = values.of({ - 'EndDate': serialize.iso8601_datetime(end_date), - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'TaskChannel': task_channel, - 'SplitByWaitTime': split_by_wait_time, - }) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) return TaskQueueStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - task_queue_sid=self._solution['task_queue_sid'], + 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) - - -class TaskQueueStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, task_queue_sid): """ - Initialize the TaskQueueStatisticsInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance - """ - super(TaskQueueStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'cumulative': payload.get('cumulative'), - 'realtime': payload.get('realtime'), - 'task_queue_sid': payload.get('task_queue_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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: 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 +class TaskQueueStatisticsList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ - return self._properties['account_sid'] + Initialize the TaskQueueStatisticsList - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the TaskQueue - :rtype: dict - """ - return self._properties['cumulative'] + :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 realtime(self): - """ - :returns: An object that contains the real-time statistics for the TaskQueue - :rtype: dict """ - return self._properties['realtime'] + super().__init__(version) - @property - def task_queue_sid(self): - """ - :returns: The SID of the TaskQueue from which these statistics were calculated - :rtype: unicode - """ - return self._properties['task_queue_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } - @property - def workspace_sid(self): + def get(self) -> TaskQueueStatisticsContext: """ - :returns: The SID of the Workspace that contains the TaskQueue - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a TaskQueueStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the TaskQueue statistics resource - :rtype: unicode """ - return self._properties['url'] + return TaskQueueStatisticsContext( + 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) -> TaskQueueStatisticsContext: """ - Fetch the TaskQueueStatisticsInstance - - :param datetime end_date: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a TaskQueueStatisticsContext - :returns: The 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 740d9a8de7..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the TaskQueue + :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: Only calculate statistics from on or before this date - :param unicode friendly_name: The friendly_name of the TaskQueue statistics to read - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics 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) + :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,226 +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']) - - 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: Only calculate statistics from on or before this date - :param unicode friendly_name: The friendly_name of the TaskQueue statistics to read - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics 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 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: Only calculate statistics from on or before this date - :param unicode friendly_name: The friendly_name of the TaskQueue statistics to read - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics 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 + 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]: """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 TaskQueuesStatisticsPage(self._version, response, self._solution) + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Asynchronously lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - 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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The SID of the Workspace that contains the TaskQueue + headers["Accept"] = "application/json" - :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) - - # 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 + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class TaskQueuesStatisticsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - 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.get('account_sid'), - 'cumulative': payload.get('cumulative'), - 'realtime': payload.get('realtime'), - 'task_queue_sid': payload.get('task_queue_sid'), - 'workspace_sid': payload.get('workspace_sid'), - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, } + Retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :param target_url: API-generated URL for the requested results page - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the TaskQueues - :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: An object that contains the real-time statistics for the TaskQueues - :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 SID of the TaskQueue from which these statistics were calculated - :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 SID of the Workspace that contains the TaskQueues - :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 b1dd263202..38aede84bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -1,713 +1,1009 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the Worker + :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 of the Worker resources to read - :param unicode activity_sid: The activity_sid of the Worker resources to read - :param unicode available: Whether to return Worker resources that are available or unavailable - :param unicode friendly_name: The friendly_name of the Worker resources to read - :param unicode target_workers_expression: Filter by Workers that would match an expression on a TaskQueue - :param unicode task_queue_name: The friendly_name of the TaskQueue that the Workers to read are eligible for - :param unicode task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for - :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']) - - 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 of the Worker resources to read - :param unicode activity_sid: The activity_sid of the Worker resources to read - :param unicode available: Whether to return Worker resources that are available or unavailable - :param unicode friendly_name: The friendly_name of the Worker resources to read - :param unicode target_workers_expression: Filter by Workers that would match an expression on a TaskQueue - :param unicode task_queue_name: The friendly_name of the TaskQueue that the Workers to read are eligible for - :param unicode task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for - :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 of the Worker resources to read - :param unicode activity_sid: The activity_sid of the Worker resources to read - :param unicode available: Whether to return Worker resources that are available or unavailable - :param unicode friendly_name: The friendly_name of the Worker resources to read - :param unicode target_workers_expression: Filter by Workers that would match an expression on a TaskQueue - :param unicode task_queue_name: The friendly_name of the TaskQueue that the Workers to read are eligible for - :param unicode task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for - :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 - """ - 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, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - 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 the WorkerInstance + Asynchronous coroutine to update the WorkerInstance - :param unicode friendly_name: A string to describe the resource - :param unicode activity_sid: The SID of a valid Activity that describes the new Worker's initial state - :param unicode attributes: A valid JSON string that describes the new Worker + :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 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(method='POST', uri=self._uri, data=data, ) - - return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) + return await self._proxy.update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) @property - def 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 of the resource to fetch - - :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 of the resource to fetch - - :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 SID of the Workspace that contains the Worker + 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) + + self._reservations: Optional[ReservationList] = None + self._worker_channels: Optional[WorkerChannelList] = None + self._statistics: Optional[WorkerStatisticsList] = None - def get_instance(self, payload): + 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({}) + + 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 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 SID of the Workspace with the Worker to fetch - :param sid: The SID of the resource to fetch - :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 the WorkerInstance + Asynchronous coroutine to fetch the WorkerInstance + :returns: The fetched WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, - reject_pending_reservations=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 SID of the Activity that describes the Worker's initial state - :param unicode attributes: The JSON string that describes the Worker - :param unicode friendly_name: A string to describe the Worker - :param bool reject_pending_reservations: Whether to reject pending reservations + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance """ - data = values.of({ - 'ActivitySid': activity_sid, - 'Attributes': attributes, - 'FriendlyName': friendly_name, - 'RejectPendingReservations': reject_pending_reservations, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return WorkerInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the WorkerInstance + Asynchronous coroutine to update the WorkerInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + :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`. - @property - def real_time_statistics(self): + :returns: The updated WorkerInstance """ - 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 - """ - 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 + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) - @property - def cumulative_statistics(self): - """ - Access the cumulative_statistics + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList - """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkersCumulativeStatisticsList( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._cumulative_statistics + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def statistics(self): - """ - Access the statistics + headers["Accept"] = "application/json" - :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'], - ) - return self._statistics + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) @property - def reservations(self): + def reservations(self) -> ReservationList: """ Access the reservations - - :returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationList """ if self._reservations is None: self._reservations = ReservationList( self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._reservations @property - def worker_channels(self): + def worker_channels(self) -> WorkerChannelList: """ Access the worker_channels - - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelList """ if self._worker_channels is None: self._worker_channels = WorkerChannelList( self._version, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['sid'], + self._solution["workspace_sid"], + self._solution["sid"], ) return self._worker_channels - def __repr__(self): + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkerStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :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 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.get('account_sid'), - 'activity_name': payload.get('activity_name'), - 'activity_sid': payload.get('activity_sid'), - 'attributes': payload.get('attributes'), - 'available': payload.get('available'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_status_changed': deserialize.iso8601_datetime(payload.get('date_status_changed')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'sid': sid or self._properties['sid'], } +class WorkerPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: """ - 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 WorkerInstance - :returns: WorkerContext for this WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = WorkerContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], - ) - return self._context + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def activity_name(self): - """ - :returns: The friendly_name of the Worker's current Activity - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['activity_name'] + return "" - @property - def activity_sid(self): - """ - :returns: The SID of the Worker's current Activity - :rtype: unicode - """ - return self._properties['activity_sid'] - @property - def attributes(self): - """ - :returns: The JSON string that describes the Worker - :rtype: unicode - """ - return self._properties['attributes'] +class WorkerList(ListResource): - @property - def available(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: Whether the Worker is available to perform tasks - :rtype: bool - """ - return self._properties['available'] + Initialize the WorkerList - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was 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 Workers to read. - @property - def date_status_changed(self): """ - :returns: The date and time in GMT of the last change to the Worker's activity - :rtype: datetime - """ - return self._properties['date_status_changed'] + super().__init__(version) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers".format(**self._solution) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + self._cumulative_statistics: Optional[WorkersCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None + self._statistics: Optional[WorkersStatisticsList] = None - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: """ - return self._properties['sid'] + Create the WorkerInstance - @property - def workspace_sid(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 SID of the Workspace that contains the Worker - :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 = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: """ - 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 absolute URL of the Worker resource - :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 URLs of related resources - :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 the 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: The 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, - reject_pending_reservations=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, + } + ) - :param unicode activity_sid: The SID of the Activity that describes the Worker's initial state - :param unicode attributes: The JSON string that describes the Worker - :param unicode friendly_name: A string to describe the Worker - :param bool reject_pending_reservations: Whether to reject pending reservations + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: The updated WorkerInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, self._solution) + + async def page_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Asynchronously retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance """ - return self._proxy.update( - activity_sid=activity_sid, - attributes=attributes, - friendly_name=friendly_name, - reject_pending_reservations=reject_pending_reservations, + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers ) + return WorkerPage(self._version, response, self._solution) - def delete(self): + 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: + """ + Access the real_time_statistics """ - return self._proxy.cumulative_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 e28caacd10..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 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that this worker is contained within. - :param worker_sid: The SID of the reserved Worker resource - - :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: Returns the list of reservations for a worker with a specified ReservationStatus - :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']) + 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: Returns the list of reservations for a worker with a specified ReservationStatus - :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: Returns the list of reservations for a worker with a specified ReservationStatus - :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 """ - data = values.of({ - 'ReservationStatus': reservation_status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 + Update the ReservationInstance - :param sid: The SID of the WorkerReservation resource to fetch + :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: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + :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 of the WorkerReservation resource to fetch + 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: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + :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 SID of the Workspace that this worker is contained within. - :param worker_sid: The SID of the reserved Worker resource + 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 + ) - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the WorkerReservation resource to fetch - :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resource to fetch - :param sid: The SID of the WorkerReservation resource to fetch + return ReservationInstance( + 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.reservation.ReservationContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext + 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: """ - super(ReservationContext, self).__init__(version) + Update the ReservationInstance - # 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) + :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`. - def fetch(self): + :returns: The updated ReservationInstance """ - Fetch the ReservationInstance - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return ReservationInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=self._solution['sid'], + 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, - end_conference_on_customer_exit=values.unset, - beep_on_customer_entrance=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: """ - Update the ReservationInstance - - :param ReservationInstance.Status reservation_status: The new status of the reservation - :param unicode worker_activity_sid: The new worker activity SID if rejecting a reservation - :param unicode instruction: The assignment instruction for the reservation - :param unicode dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction - :param unicode dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction - :param unicode dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction - :param unicode dequeue_timeout: The timeout for call when executing a Dequeue instruction - :param unicode dequeue_to: The contact URI of the worker when executing a Dequeue instruction - :param unicode dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction - :param unicode call_from: The Caller ID of the outbound call when executing a Call instruction - :param unicode call_record: Whether to record both legs of a call when executing a Call instruction - :param unicode call_timeout: The timeout for a call when executing a Call instruction - :param unicode call_to: The contact URI of the worker when executing a Call instruction - :param unicode call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction - :param unicode call_status_callback_url: The URL to call for the completed call event when executing a Call instruction - :param bool call_accept: Whether to accept a reservation when executing a Call instruction - :param unicode redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction - :param bool redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction - :param unicode redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction - :param unicode to: The Contact URI of the worker when executing a Conference instruction - :param unicode from_: The caller ID of the call to the worker when executing a Conference instruction - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param ReservationInstance.CallStatus status_callback_event: The call progress events that we will send to status_callback - :param unicode timeout: The timeout for a call when executing a Conference instruction - :param bool record: Whether to record the participant and their conferences - :param bool muted: Whether to mute the agent - :param unicode beep: Whether to play a notification beep when the participant joins - :param bool start_conference_on_enter: Whether the conference starts when the participant joins the conference - :param bool end_conference_on_exit: Whether to end the conference when the agent leaves - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool early_media: Whether agents can hear the state of the outbound call - :param unicode max_participants: The maximum number of agent conference participants - :param unicode conference_status_callback: The callback URL for conference events - :param unicode conference_status_callback_method: HTTP method for requesting `conference_status_callback` URL - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference status events that we will send to conference_status_callback - :param unicode conference_record: Whether to record the conference the participant is joining - :param unicode conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files - :param unicode recording_channels: Specify `mono` or `dual` recording channels - :param unicode recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes - :param unicode recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback` - :param unicode conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available - :param unicode conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback` - :param unicode region: The region where we should mix the conference audio - :param unicode sip_auth_username: The SIP username used for authentication - :param unicode sip_auth_password: The SIP password for authentication - :param unicode dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction - :param unicode post_work_activity_sid: The new worker activity SID after executing a Conference instruction - :param bool end_conference_on_customer_exit: Whether to end the conference when the customer leaves - :param bool beep_on_customer_entrance: Whether to play a notification beep when the customer joins + 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 - :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, - 'EndConferenceOnCustomerExit': end_conference_on_customer_exit, - 'BeepOnCustomerEntrance': beep_on_customer_entrance, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return ReservationInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=self._solution['sid'], + 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" - WRAPPING = "wrapping" - COMPLETED = "completed" +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.get('account_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'reservation_status': payload.get('reservation_status'), - 'sid': payload.get('sid'), - 'task_sid': payload.get('task_sid'), - 'worker_name': payload.get('worker_name'), - 'worker_sid': payload.get('worker_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - 'links': payload.get('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): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: """ - 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 ISO 8601 date and time in GMT when the resource was 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 ISO 8601 date and time in GMT when the resource was last 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 current status of the reservation - :rtype: ReservationInstance.Status - """ - return self._properties['reservation_status'] + return self._version.stream(page, limits["limit"]) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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['sid'] + 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 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. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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 of the reserved Task resource - :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['task_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 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 friendly_name of the Worker that is reserved - :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['worker_name'] + 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_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 SID of the reserved Worker resource - :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_sid'] + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def workspace_sid(self): + :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 """ - :returns: The SID of the Workspace that this worker is contained within. - :rtype: unicode + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: """ - return self._properties['workspace_sid'] + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately - @property - def url(self): + :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 """ - :returns: The absolute URL of the WorkerReservation resource - :rtype: unicode + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: """ - return self._properties['url'] + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately - @property - def links(self): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance """ - :returns: The URLs of related resources - :rtype: unicode + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: """ - return self._properties['links'] + Asynchronously retrieve a specific page of ReservationInstance 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 ReservationInstance """ - Fetch the ReservationInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) - :returns: The fetched ReservationInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance + def get(self, sid: str) -> ReservationContext: """ - return self._proxy.fetch() + Constructs a ReservationContext - 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, - end_conference_on_customer_exit=values.unset, - beep_on_customer_entrance=values.unset): + :param sid: The SID of the WorkerReservation resource to update. """ - Update the ReservationInstance + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) - :param ReservationInstance.Status reservation_status: The new status of the reservation - :param unicode worker_activity_sid: The new worker activity SID if rejecting a reservation - :param unicode instruction: The assignment instruction for the reservation - :param unicode dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction - :param unicode dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction - :param unicode dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction - :param unicode dequeue_timeout: The timeout for call when executing a Dequeue instruction - :param unicode dequeue_to: The contact URI of the worker when executing a Dequeue instruction - :param unicode dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction - :param unicode call_from: The Caller ID of the outbound call when executing a Call instruction - :param unicode call_record: Whether to record both legs of a call when executing a Call instruction - :param unicode call_timeout: The timeout for a call when executing a Call instruction - :param unicode call_to: The contact URI of the worker when executing a Call instruction - :param unicode call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction - :param unicode call_status_callback_url: The URL to call for the completed call event when executing a Call instruction - :param bool call_accept: Whether to accept a reservation when executing a Call instruction - :param unicode redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction - :param bool redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction - :param unicode redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction - :param unicode to: The Contact URI of the worker when executing a Conference instruction - :param unicode from_: The caller ID of the call to the worker when executing a Conference instruction - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param ReservationInstance.CallStatus status_callback_event: The call progress events that we will send to status_callback - :param unicode timeout: The timeout for a call when executing a Conference instruction - :param bool record: Whether to record the participant and their conferences - :param bool muted: Whether to mute the agent - :param unicode beep: Whether to play a notification beep when the participant joins - :param bool start_conference_on_enter: Whether the conference starts when the participant joins the conference - :param bool end_conference_on_exit: Whether to end the conference when the agent leaves - :param unicode wait_url: URL that hosts pre-conference hold music - :param unicode wait_method: The HTTP method we should use to call `wait_url` - :param bool early_media: Whether agents can hear the state of the outbound call - :param unicode max_participants: The maximum number of agent conference participants - :param unicode conference_status_callback: The callback URL for conference events - :param unicode conference_status_callback_method: HTTP method for requesting `conference_status_callback` URL - :param ReservationInstance.ConferenceEvent conference_status_callback_event: The conference status events that we will send to conference_status_callback - :param unicode conference_record: Whether to record the conference the participant is joining - :param unicode conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files - :param unicode recording_channels: Specify `mono` or `dual` recording channels - :param unicode recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes - :param unicode recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback` - :param unicode conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available - :param unicode conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback` - :param unicode region: The region where we should mix the conference audio - :param unicode sip_auth_username: The SIP username used for authentication - :param unicode sip_auth_password: The SIP password for authentication - :param unicode dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction - :param unicode post_work_activity_sid: The new worker activity SID after executing a Conference instruction - :param bool end_conference_on_customer_exit: Whether to end the conference when the customer leaves - :param bool beep_on_customer_entrance: Whether to play a notification beep when the customer joins + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext - :returns: The 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, - end_conference_on_customer_exit=end_conference_on_customer_exit, - beep_on_customer_entrance=beep_on_customer_entrance, + 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 3c20dd3011..6e3cc9c1dd 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -1,461 +1,594 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the WorkerChannel - :param worker_sid: The SID of the Worker that contains the WorkerChannel - - :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) - - # 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=None, page_size=None): - """ - 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) - - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) +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") - return self._version.stream(page, limits['limit']) + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerChannelContext] = None - def list(self, limit=None, page_size=None): + @property + def _proxy(self) -> "WorkerChannelContext": """ - 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) + 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 """ - return list(self.stream(limit=limit, page_size=page_size, )) + 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 page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def fetch(self) -> "WorkerChannelInstance": """ - Retrieve a single page of WorkerChannelInstance records from the API. - Request is executed immediately + Fetch the WorkerChannelInstance - :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 WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + :returns: The fetched WorkerChannelInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return WorkerChannelPage(self._version, response, self._solution) + return self._proxy.fetch() - def get_page(self, target_url): + async def fetch_async(self) -> "WorkerChannelInstance": """ - Retrieve a specific page of WorkerChannelInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the WorkerChannelInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelPage + :returns: The fetched WorkerChannelInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return WorkerChannelPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get(self, sid): + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": """ - Constructs a WorkerChannelContext + Update the WorkerChannelInstance - :param sid: The SID of the to fetch + :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 of the to fetch + :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 SID of the Workspace that contains the WorkerChannel - :param worker_sid: The SID of the Worker that contains the WorkerChannel + 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 SID of the Workspace with the WorkerChannel to fetch - :param worker_sid: The SID of the Worker with the WorkerChannel to fetch - :param sid: The SID of the to fetch + 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 the WorkerChannelInstance - :returns: The fetched WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return WorkerChannelInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - worker_sid=self._solution['worker_sid'], - sid=self._solution['sid'], + 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 total number of Tasks that the Worker should handle for the TaskChannel type - :param bool available: Whether the WorkerChannel is 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: The updated WorkerChannelInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance """ - data = values.of({'Capacity': capacity, 'Available': available, }) - payload = self._version.update(method='POST', uri=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.get('account_sid'), - 'assigned_tasks': deserialize.integer(payload.get('assigned_tasks')), - 'available': payload.get('available'), - 'available_capacity_percentage': deserialize.integer(payload.get('available_capacity_percentage')), - 'configured_capacity': deserialize.integer(payload.get('configured_capacity')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'sid': payload.get('sid'), - 'task_channel_sid': payload.get('task_channel_sid'), - 'task_channel_unique_name': payload.get('task_channel_unique_name'), - 'worker_sid': payload.get('worker_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assigned_tasks(self): - """ - :returns: The total number of Tasks assigned to Worker for the TaskChannel type - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assigned_tasks'] + return "" - @property - def available(self): - """ - :returns: Whether the Worker should receive Tasks of the TaskChannel type - :rtype: bool - """ - return self._properties['available'] - @property - def available_capacity_percentage(self): - """ - :returns: The current available capacity between 0 to 100 for the TaskChannel - :rtype: unicode - """ - return self._properties['available_capacity_percentage'] +class WorkerChannelList(ListResource): - @property - def configured_capacity(self): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - :returns: The current configured capacity for the WorkerChannel - :rtype: unicode - """ - 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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 unique string that identifies the 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[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 SID of the TaskChannel - :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 unique name of the TaskChannel, such as 'voice' or 'sms' - :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 SID of the Worker that contains the WorkerChannel - :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 SID of the Workspace that contains the WorkerChannel - :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 absolute URL of the WorkerChannel resource - :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 the WorkerChannelInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) - :returns: The 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 total number of Tasks that the Worker should handle for the TaskChannel type - :param bool available: Whether the WorkerChannel is available + def __call__(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext - :returns: The 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 9e4b2a594d..eea670aa7d 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -1,288 +1,292 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the WorkerChannel - :param worker_sid: The SID of the Worker that contains the WorkerChannel + 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 - :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance """ - return 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 SID of the Workspace that contains the WorkerChannel - :param worker_sid: The SID of the Worker that contains the WorkerChannel + 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 SID of the Workspace with the WorkerChannel to fetch - :param worker_sid: The SID of the Worker with the WorkerChannel to fetch + :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) + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset): - """ - Fetch the WorkerStatisticsInstance + headers = values.of({}) - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode task_channel: Only calculate statistics on this TaskChannel + headers["Accept"] = "application/json" - :returns: The fetched WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance - """ - data = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + 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.get('account_sid'), - 'cumulative': payload.get('cumulative'), - 'worker_sid': payload.get('worker_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'workspace_sid': workspace_sid, 'worker_sid': worker_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 WorkerStatisticsList(ListResource): - :returns: WorkerStatisticsContext for this WorkerStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsContext + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ - 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 + Initialize the WorkerStatisticsList - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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 cumulative(self): """ - :returns: An object that contains the cumulative statistics for the Worker - :rtype: dict - """ - return self._properties['cumulative'] + super().__init__(version) - @property - def worker_sid(self): - """ - :returns: The SID of the Worker that contains the WorkerChannel - :rtype: unicode - """ - return self._properties['worker_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the WorkerChannel - :rtype: unicode + def get(self) -> WorkerStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkerStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the WorkerChannel statistics resource - :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 the WorkerStatisticsInstance - - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode task_channel: Only calculate statistics on this TaskChannel + Constructs a WorkerStatisticsContext - :returns: The 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 16627ecaf4..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,344 +1,308 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +from twilio.base.version import Version - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersCumulativeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workers - - :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, } - - 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 SID of the Workspace that contains the Workers + :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 SID of the Workspace with the resource to fetch - - :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 the WorkersCumulativeStatisticsInstance - :param datetime end_date: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :returns: The fetched WorkersCumulativeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsInstance """ - data = values.of({ - 'EndDate': serialize.iso8601_datetime(end_date), - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'TaskChannel': task_channel, - }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) return WorkersCumulativeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + 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.get('account_sid'), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'activity_durations': payload.get('activity_durations'), - 'reservations_created': deserialize.integer(payload.get('reservations_created')), - 'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')), - 'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')), - 'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')), - 'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')), - 'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 SID of the Account that created the resource - :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 beginning of the interval during which these statistics were calculated - :rtype: datetime + def __repr__(self) -> str: """ - return self._properties['start_time'] + Provide a friendly representation - @property - def end_time(self): - """ - :returns: The end of the interval during which these statistics were calculated - :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 minimum, average, maximum, and total time that Workers spent in each Activity - :rtype: dict - """ - return self._properties['activity_durations'] - @property - def reservations_created(self): - """ - :returns: The total number of Reservations that were created - :rtype: unicode - """ - return self._properties['reservations_created'] +class WorkersCumulativeStatisticsList(ListResource): - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations that were accepted - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['reservations_accepted'] + Initialize the WorkersCumulativeStatisticsList - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. - @property - def reservations_timed_out(self): """ - :returns: The total number of Reservations that were timed out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] - - @property - def reservations_canceled(self): - """ - :returns: The total number of Reservations that were canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + super().__init__(version) - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations that were rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Workers - :rtype: unicode + def get(self) -> WorkersCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkersCumulativeStatisticsContext - @property - def url(self): """ - :returns: The absolute URL of the Workers statistics resource - :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 the WorkersCumulativeStatisticsInstance - - :param datetime end_date: Only calculate statistics from on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel + Constructs a WorkersCumulativeStatisticsContext - :returns: The 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 6f448284a7..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,262 +1,239 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the Workers + 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 SID of the Workspace that contains the Workers + 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 SID of the Workspace with the resource to fetch + :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 the WorkersRealTimeStatisticsInstance + data = values.of( + { + "TaskChannel": task_channel, + } + ) - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + headers = values.of({}) - :returns: The fetched WorkersRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance - """ - data = values.of({'TaskChannel': task_channel, }) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + 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.get('account_sid'), - 'activity_statistics': payload.get('activity_statistics'), - 'total_workers': deserialize.integer(payload.get('total_workers')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 SID of the Account that created the resource - :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 number of current Workers by Activity - :rtype: dict - """ - return self._properties['activity_statistics'] + super().__init__(version) - @property - def total_workers(self): - """ - :returns: The total number of Workers - :rtype: unicode - """ - return self._properties['total_workers'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Workers - :rtype: unicode + def get(self) -> WorkersRealTimeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkersRealTimeStatisticsContext - @property - def url(self): """ - :returns: The absolute URL of the Workers statistics resource - :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 the WorkersRealTimeStatisticsInstance - - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + Constructs a WorkersRealTimeStatisticsContext - :returns: The 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 50f8dd113b..31c79ee6ba 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -1,290 +1,308 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 WorkersStatisticsList(ListResource): - """ """ +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 __init__(self, version, workspace_sid): + @property + def _proxy(self) -> "WorkersStatisticsContext": """ - Initialize the WorkersStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Worker + 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.WorkersStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList + :returns: WorkersStatisticsContext for this WorkersStatisticsInstance """ - super(WorkersStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } + if self._context is None: + self._context = WorkersStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_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_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": """ - Constructs a WorkersStatisticsContext + Fetch the WorkersStatisticsInstance - :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'], ) + :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`. - def __call__(self): + :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, + ) + + 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: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext + :returns: The fetched WorkersStatisticsInstance """ - return WorkersStatisticsContext(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_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 SID of the Workspace that contains the Worker + 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): + 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: """ - Build an instance of WorkersStatisticsInstance + Fetch the WorkersStatisticsInstance - :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_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: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance + :returns: The fetched WorkersStatisticsInstance """ - return WorkersStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - ) - def __repr__(self): - """ - Provide a friendly representation + 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, + } + ) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers = values.of({}) + headers["Accept"] = "application/json" -class WorkersStatisticsContext(InstanceContext): - """ """ + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - def __init__(self, version, workspace_sid): - """ - Initialize the WorkersStatisticsContext + return WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the Worker to fetch + 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: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext + :returns: The fetched WorkersStatisticsInstance """ - super(WorkersStatisticsContext, self).__init__(version) - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workers/Statistics'.format(**self._solution) + 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, + } + ) - 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 the WorkersStatisticsInstance + headers = values.of({}) - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics - :param unicode task_queue_name: The friendly_name of the TaskQueue for which to fetch Worker statistics - :param unicode friendly_name: Only include Workers with `friendly_name` values that match this parameter - :param unicode task_channel: Only calculate statistics on this TaskChannel + headers["Accept"] = "application/json" - :returns: The fetched WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + 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) - - -class WorkersStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid): - """ - Initialize the WorkersStatisticsInstance - - :returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsInstance """ - super(WorkersStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'realtime': payload.get('realtime'), - 'cumulative': payload.get('cumulative'), - 'account_sid': payload.get('account_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 WorkersStatisticsList(ListResource): - :returns: WorkersStatisticsContext for this WorkersStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsContext + def __init__(self, version: Version, workspace_sid: str): """ - if self._context is None: - self._context = WorkersStatisticsContext( - self._version, - workspace_sid=self._solution['workspace_sid'], - ) - return self._context + Initialize the WorkersStatisticsList - @property - def realtime(self): - """ - :returns: An object that contains the real-time statistics for the Worker - :rtype: dict - """ - return self._properties['realtime'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. - @property - def cumulative(self): """ - :returns: An object that contains the cumulative statistics for the Worker - :rtype: dict - """ - return self._properties['cumulative'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace that contains the Worker - :rtype: unicode + def get(self) -> WorkersStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkersStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the Worker statistics resource - :rtype: unicode """ - return self._properties['url'] + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - 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): + def __call__(self) -> WorkersStatisticsContext: """ - Fetch the WorkersStatisticsInstance - - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics - :param unicode task_queue_name: The friendly_name of the TaskQueue for which to fetch Worker statistics - :param unicode friendly_name: Only include Workers with `friendly_name` values that match this parameter - :param unicode task_channel: Only calculate statistics on this TaskChannel + Constructs a WorkersStatisticsContext - :returns: The 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 5dc3887d8b..619ae1bce9 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -1,606 +1,837 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace that contains the Workflow + :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 of the Workflow resources to read - :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']) + :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 of the Workflow resources to read - :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 of the Workflow resources to read - :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 """ - data = values.of({ - 'FriendlyName': friendly_name, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return WorkflowPage(self._version, response, self._solution) - - 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) + 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. - def create(self, friendly_name, configuration, - assignment_callback_url=values.unset, - fallback_assignment_callback_url=values.unset, - task_reservation_timeout=values.unset): + :returns: The updated WorkflowInstance """ - Create the WorkflowInstance - - :param unicode friendly_name: descriptive string that you create to describe the Workflow resource - :param unicode configuration: A JSON string that contains the rules to apply to the Workflow - :param unicode assignment_callback_url: The URL from your application that will process task assignment events - :param unicode fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails - :param unicode task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker + 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, + ) - :returns: The created WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ - 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(method='POST', uri=self._uri, data=data, ) - - return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], ) - - def get(self, sid): + Access the cumulative_statistics """ - Constructs a WorkflowContext - - :param sid: The SID of the resource + return self._proxy.cumulative_statistics - :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowContext + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) - - def __call__(self, sid): + Access the real_time_statistics """ - Constructs a WorkflowContext - - :param sid: The SID of the resource + 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: """ - return WorkflowContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, ) + Access the statistics + """ + 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 SID of the Workspace that contains the Workflow + 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 + ) + + self._cumulative_statistics: Optional[WorkflowCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None + self._statistics: Optional[WorkflowStatisticsList] = None - def get_instance(self, payload): + 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 SID of the Workspace with the Workflow to fetch - :param sid: The SID of the resource - :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) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> WorkflowInstance: """ - Fetch the WorkflowInstance + Asynchronous coroutine to fetch the WorkflowInstance + :returns: The fetched WorkflowInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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, - re_evaluate_tasks=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: descriptive string that you create to describe the Workflow resource - :param unicode assignment_callback_url: The URL from your application that will process task assignment events - :param unicode fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails - :param unicode configuration: A JSON string that contains the rules to apply to the Workflow - :param unicode task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker - :param unicode re_evaluate_tasks: Whether or not to re-evaluate Tasks + :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 - :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, - 'ReEvaluateTasks': re_evaluate_tasks, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) return WorkflowInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - sid=self._solution['sid'], + 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: True if delete succeeds, False otherwise - :rtype: bool + :returns: The updated WorkflowInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) @property - def 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.get('account_sid'), - 'assignment_callback_url': payload.get('assignment_callback_url'), - 'configuration': payload.get('configuration'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'document_content_type': payload.get('document_content_type'), - 'fallback_assignment_callback_url': payload.get('fallback_assignment_callback_url'), - 'friendly_name': payload.get('friendly_name'), - 'sid': payload.get('sid'), - 'task_reservation_timeout': deserialize.integer(payload.get('task_reservation_timeout')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - 'links': payload.get('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): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def assignment_callback_url(self): - """ - :returns: The URL that we call when a task managed by the Workflow is assigned to a Worker - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['assignment_callback_url'] + return "" - @property - def configuration(self): - """ - :returns: A JSON string that contains the Workflow's configuration - :rtype: unicode - """ - return self._properties['configuration'] - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] +class WorkflowList(ListResource): - @property - def date_updated(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + Initialize the WorkflowList - @property - def document_content_type(self): - """ - :returns: The MIME type of the document - :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 URL that we call when a call to the `assignment_callback_url` fails - :rtype: unicode """ - return self._properties['fallback_assignment_callback_url'] + super().__init__(version) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the Workflow resource - :rtype: unicode - """ - return self._properties['friendly_name'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) - @property - def sid(self): + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def task_reservation_timeout(self): + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: """ - :returns: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker - :rtype: unicode + 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 """ - return self._properties['task_reservation_timeout'] - @property - def workspace_sid(self): + 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 SID of the Workspace that contains the Workflow - :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 absolute URL of the Workflow resource - :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 URLs of related resources - :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 the WorkflowInstance + Retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately - :returns: The 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, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" - 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, - re_evaluate_tasks=values.unset): + 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: descriptive string that you create to describe the Workflow resource - :param unicode assignment_callback_url: The URL from your application that will process task assignment events - :param unicode fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails - :param unicode configuration: A JSON string that contains the rules to apply to the Workflow - :param unicode task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker - :param unicode re_evaluate_tasks: Whether or not to re-evaluate Tasks + :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: The 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, - re_evaluate_tasks=re_evaluate_tasks, + 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 - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + :param target_url: API-generated URL for the requested results page + + :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 70675666c5..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,448 +1,376 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workflow. - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value - - :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, } +from twilio.base.version import Version - 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 SID of the Workspace that contains the Workflow. - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value + :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 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 - - :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): + 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 datetime end_date: Only include usage that occurred on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - return WorkflowCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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, + } ) - 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.get('account_sid'), - 'avg_task_acceptance_time': deserialize.integer(payload.get('avg_task_acceptance_time')), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'reservations_created': deserialize.integer(payload.get('reservations_created')), - 'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')), - 'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')), - 'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')), - 'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')), - 'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')), - 'split_by_wait_time': payload.get('split_by_wait_time'), - 'wait_duration_until_accepted': payload.get('wait_duration_until_accepted'), - 'wait_duration_until_canceled': payload.get('wait_duration_until_canceled'), - 'tasks_canceled': deserialize.integer(payload.get('tasks_canceled')), - 'tasks_completed': deserialize.integer(payload.get('tasks_completed')), - 'tasks_entered': deserialize.integer(payload.get('tasks_entered')), - 'tasks_deleted': deserialize.integer(payload.get('tasks_deleted')), - 'tasks_moved': deserialize.integer(payload.get('tasks_moved')), - 'tasks_timed_out_in_workflow': deserialize.integer(payload.get('tasks_timed_out_in_workflow')), - 'workflow_sid': payload.get('workflow_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 + headers = values.of({}) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def avg_task_acceptance_time(self): - """ - :returns: The average time in seconds between Task creation and acceptance - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def start_time(self): - """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - @property - def end_time(self): + 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: """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['end_time'] + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance - @property - def reservations_created(self): - """ - :returns: The total number of Reservations that were created for Workers - :rtype: unicode - """ - return self._properties['reservations_created'] + :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. - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted by Workers - :rtype: unicode + :returns: The fetched WorkflowCumulativeStatisticsInstance """ - return self._properties['reservations_accepted'] - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + 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 total number of Reservations that were timed out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers = values.of({}) - @property - def reservations_canceled(self): - """ - :returns: The total number of Reservations that were canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] - - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations that were rescinded - :rtype: unicode - """ - return self._properties['reservations_rescinded'] + headers["Accept"] = "application/json" - @property - def split_by_wait_time(self): - """ - :returns: A list of objects that describe the Tasks canceled and reservations accepted above and below the specified thresholds - :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 statistics for Tasks that were 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 statistics for Tasks that were 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 total number of Tasks that were 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 total number of Tasks that were completed - :rtype: unicode - """ - return self._properties['tasks_completed'] - @property - def tasks_entered(self): - """ - :returns: The total number of Tasks that entered the Workflow - :rtype: unicode - """ - return self._properties['tasks_entered'] +class WorkflowCumulativeStatisticsList(ListResource): - @property - def tasks_deleted(self): - """ - :returns: The total number of Tasks that were 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 total number of Tasks that were moved from one queue to another - :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 total number of Tasks that were timed out of their Workflows - :rtype: unicode """ - return self._properties['tasks_timed_out_in_workflow'] + super().__init__(version) - @property - def workflow_sid(self): - """ - :returns: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value - :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 SID of the Workspace that contains the Workflow. - :rtype: unicode + def get(self) -> WorkflowCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkflowCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the Workflow statistics resource - :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 the WorkflowCumulativeStatisticsInstance - - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a WorkflowCumulativeStatisticsContext - :returns: The 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 c6d143073e..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,306 +1,271 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, workspace_sid, workflow_sid): - """ - Initialize the WorkflowRealTimeStatisticsList +from twilio.base.version import Version - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workflow. - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value - :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 SID of the Workspace that contains the Workflow. - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value + :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 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 - - :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 the WorkflowRealTimeStatisticsInstance - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsInstance """ - data = values.of({'TaskChannel': task_channel, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) return WorkflowRealTimeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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.get('account_sid'), - 'longest_task_waiting_age': deserialize.integer(payload.get('longest_task_waiting_age')), - 'longest_task_waiting_sid': payload.get('longest_task_waiting_sid'), - 'tasks_by_priority': payload.get('tasks_by_priority'), - 'tasks_by_status': payload.get('tasks_by_status'), - 'total_tasks': deserialize.integer(payload.get('total_tasks')), - 'workflow_sid': payload.get('workflow_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 - - :returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsContext - """ - 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 + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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 longest_task_waiting_age(self): - """ - :returns: The age of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_age'] - @property - def longest_task_waiting_sid(self): - """ - :returns: The SID of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_sid'] +class WorkflowRealTimeStatisticsList(ListResource): - @property - def tasks_by_priority(self): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - :returns: The number of Tasks by priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] + Initialize the WorkflowRealTimeStatisticsList - @property - def tasks_by_status(self): - """ - :returns: The number of Tasks by their current 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 number of Tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + super().__init__(version) - @property - def workflow_sid(self): - """ - :returns: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value - :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 SID of the Workspace that contains the Workflow. - :rtype: unicode + def get(self) -> WorkflowRealTimeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkflowRealTimeStatisticsContext - @property - def url(self): """ - :returns: The absolute URL of the Workflow statistics resource - :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 the WorkflowRealTimeStatisticsInstance - - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + Constructs a WorkflowRealTimeStatisticsContext - :returns: The 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 12f692de2c..e49bd32d6e 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -1,303 +1,306 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 WorkflowStatisticsList(ListResource): - """ """ +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 - def __init__(self, version, workspace_sid, workflow_sid): + @property + def _proxy(self) -> "WorkflowStatisticsContext": """ - Initialize the WorkflowStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace that contains the Workflow - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value + 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.workflow.workflow_statistics.WorkflowStatisticsList - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsList + :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance """ - super(WorkflowStatisticsList, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } + if self._context is None: + self._context = WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context - def 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, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": """ - Constructs a WorkflowStatisticsContext + 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: 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 __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, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": """ - Constructs a WorkflowStatisticsContext + 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: 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 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 WorkflowStatisticsPage(Page): - """ """ +class WorkflowStatisticsContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - Initialize the WorkflowStatisticsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param workspace_sid: The SID of the Workspace that contains the Workflow - :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value + Initialize the WorkflowStatisticsContext - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsPage - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsPage + :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(WorkflowStatisticsPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workflows/{workflow_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, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: """ - Build an instance of WorkflowStatisticsInstance + 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'], + + 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 __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 WorkflowStatisticsContext(InstanceContext): - """ """ + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) - def __init__(self, version, workspace_sid, workflow_sid): + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: """ - Initialize the WorkflowStatisticsContext + Asynchronous coroutine to fetch the WorkflowStatisticsInstance - :param Version 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 + :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 """ - super(WorkflowStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, 'workflow_sid': workflow_sid, } - self._uri = '/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/Statistics'.format(**self._solution) - def fetch(self, minutes=values.unset, start_date=values.unset, - end_date=values.unset, task_channel=values.unset, - split_by_wait_time=values.unset): - """ - Fetch the 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: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + headers = values.of({}) - :returns: The fetched WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - """ - data = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - 'SplitByWaitTime': split_by_wait_time, - }) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) return WorkflowStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], - workflow_sid=self._solution['workflow_sid'], + 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) - - -class WorkflowStatisticsInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, workspace_sid, workflow_sid): """ - Initialize the WorkflowStatisticsInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics.WorkflowStatisticsInstance - """ - super(WorkflowStatisticsInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'cumulative': payload.get('cumulative'), - 'realtime': payload.get('realtime'), - 'workflow_sid': payload.get('workflow_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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: 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 +class WorkflowStatisticsList(ListResource): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ - return self._properties['account_sid'] + Initialize the WorkflowStatisticsList - @property - def cumulative(self): - """ - :returns: An object that contains the cumulative statistics for the Workflow - :rtype: dict - """ - return self._properties['cumulative'] + :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 realtime(self): - """ - :returns: An object that contains the real-time statistics for the Workflow - :rtype: dict """ - return self._properties['realtime'] + super().__init__(version) - @property - def workflow_sid(self): - """ - :returns: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value - :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) -> WorkflowStatisticsContext: """ - :returns: The SID of the Workspace that contains the Workflow - :rtype: unicode - """ - return self._properties['workspace_sid'] + Constructs a WorkflowStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the Workflow statistics resource - :rtype: unicode """ - return self._properties['url'] + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_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) -> WorkflowStatisticsContext: """ - Fetch the WorkflowStatisticsInstance - - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a WorkflowStatisticsContext - :returns: The 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 b60dc11217..3747b395d2 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -1,431 +1,356 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 +from twilio.base.version import Version -class WorkspaceCumulativeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceCumulativeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace - - :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 SID of the Workspace + :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 SID of the Workspace to fetch - - :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): + 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 datetime end_date: Only include usage that occurred on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.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, - }) - - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) - return WorkspaceCumulativeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + 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, + } ) - 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.get('account_sid'), - 'avg_task_acceptance_time': deserialize.integer(payload.get('avg_task_acceptance_time')), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'reservations_created': deserialize.integer(payload.get('reservations_created')), - 'reservations_accepted': deserialize.integer(payload.get('reservations_accepted')), - 'reservations_rejected': deserialize.integer(payload.get('reservations_rejected')), - 'reservations_timed_out': deserialize.integer(payload.get('reservations_timed_out')), - 'reservations_canceled': deserialize.integer(payload.get('reservations_canceled')), - 'reservations_rescinded': deserialize.integer(payload.get('reservations_rescinded')), - 'split_by_wait_time': payload.get('split_by_wait_time'), - 'wait_duration_until_accepted': payload.get('wait_duration_until_accepted'), - 'wait_duration_until_canceled': payload.get('wait_duration_until_canceled'), - 'tasks_canceled': deserialize.integer(payload.get('tasks_canceled')), - 'tasks_completed': deserialize.integer(payload.get('tasks_completed')), - 'tasks_created': deserialize.integer(payload.get('tasks_created')), - 'tasks_deleted': deserialize.integer(payload.get('tasks_deleted')), - 'tasks_moved': deserialize.integer(payload.get('tasks_moved')), - 'tasks_timed_out_in_workflow': deserialize.integer(payload.get('tasks_timed_out_in_workflow')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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 + headers = values.of({}) - :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 + headers["Accept"] = "application/json" - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def avg_task_acceptance_time(self): - """ - :returns: The average time in seconds between Task creation and acceptance - :rtype: unicode - """ - return self._properties['avg_task_acceptance_time'] + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) - @property - def start_time(self): - """ - :returns: The beginning of the interval during which these statistics were calculated - :rtype: datetime - """ - return self._properties['start_time'] + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def end_time(self): - """ - :returns: The end of the interval during which these statistics were calculated - :rtype: datetime + 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: """ - return self._properties['end_time'] + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance - @property - def reservations_created(self): - """ - :returns: The total number of Reservations that were created for Workers - :rtype: unicode - """ - return self._properties['reservations_created'] + :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. - @property - def reservations_accepted(self): - """ - :returns: The total number of Reservations accepted by Workers - :rtype: unicode + :returns: The fetched WorkspaceCumulativeStatisticsInstance """ - return self._properties['reservations_accepted'] - @property - def reservations_rejected(self): - """ - :returns: The total number of Reservations that were rejected - :rtype: unicode - """ - return self._properties['reservations_rejected'] + 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 total number of Reservations that were timed out - :rtype: unicode - """ - return self._properties['reservations_timed_out'] + headers = values.of({}) - @property - def reservations_canceled(self): - """ - :returns: The total number of Reservations that were canceled - :rtype: unicode - """ - return self._properties['reservations_canceled'] + headers["Accept"] = "application/json" - @property - def reservations_rescinded(self): - """ - :returns: The total number of Reservations that were 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: A list of objects that describe the Tasks canceled and reservations accepted above and below the specified thresholds - :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): - """ - :returns: The wait duration statistics for Tasks that were accepted - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['wait_duration_until_accepted'] + Provide a friendly representation - @property - def wait_duration_until_canceled(self): - """ - :returns: The wait duration statistics for Tasks that were 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 total number of Tasks that were canceled - :rtype: unicode - """ - return self._properties['tasks_canceled'] - @property - def tasks_completed(self): - """ - :returns: The total number of Tasks that were completed - :rtype: unicode - """ - return self._properties['tasks_completed'] +class WorkspaceCumulativeStatisticsList(ListResource): - @property - def tasks_created(self): + def __init__(self, version: Version, workspace_sid: str): """ - :returns: The total number of Tasks created - :rtype: unicode - """ - return self._properties['tasks_created'] + Initialize the WorkspaceCumulativeStatisticsList - @property - def tasks_deleted(self): - """ - :returns: The total number of Tasks that were 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 total number of Tasks that were moved from one queue to another - :rtype: unicode - """ - return self._properties['tasks_moved'] + super().__init__(version) - @property - def tasks_timed_out_in_workflow(self): - """ - :returns: The total number of Tasks that were timed out of their Workflows - :rtype: unicode - """ - return self._properties['tasks_timed_out_in_workflow'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace - :rtype: unicode + def get(self) -> WorkspaceCumulativeStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkspaceCumulativeStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the Workspace statistics resource - :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 the WorkspaceCumulativeStatisticsInstance - - :param datetime end_date: Only include usage that occurred on or before this date - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param unicode task_channel: Only calculate cumulative statistics on this TaskChannel - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a WorkspaceCumulativeStatisticsContext - :returns: The 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 07085478aa..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,307 +1,259 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 WorkspaceRealTimeStatisticsList(ListResource): - """ """ - - def __init__(self, version, workspace_sid): - """ - Initialize the WorkspaceRealTimeStatisticsList - - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace - - :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 SID of the Workspace + :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 SID of the Workspace to fetch - - :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 the WorkspaceRealTimeStatisticsInstance - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + :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 - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstance """ - data = values.of({'TaskChannel': task_channel, }) - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) return WorkspaceRealTimeStatisticsInstance( self._version, payload, - workspace_sid=self._solution['workspace_sid'], + 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) - - -class WorkspaceRealTimeStatisticsInstance(InstanceResource): - """ """ + :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`. - def __init__(self, version, payload, workspace_sid): + :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - Initialize the WorkspaceRealTimeStatisticsInstance - :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.get('account_sid'), - 'activity_statistics': payload.get('activity_statistics'), - 'longest_task_waiting_age': deserialize.integer(payload.get('longest_task_waiting_age')), - 'longest_task_waiting_sid': payload.get('longest_task_waiting_sid'), - 'tasks_by_priority': payload.get('tasks_by_priority'), - 'tasks_by_status': payload.get('tasks_by_status'), - 'total_tasks': deserialize.integer(payload.get('total_tasks')), - 'total_workers': deserialize.integer(payload.get('total_workers')), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('url'), - } + data = values.of( + { + "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: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsContext - """ - if self._context is None: - self._context = WorkspaceRealTimeStatisticsContext( - 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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - @property - def activity_statistics(self): - """ - :returns: The number of current Workers by Activity - :rtype: dict + def __repr__(self) -> str: """ - return self._properties['activity_statistics'] + Provide a friendly representation - @property - def longest_task_waiting_age(self): - """ - :returns: The age of the longest waiting Task - :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 longest_task_waiting_sid(self): - """ - :returns: The SID of the longest waiting Task - :rtype: unicode - """ - return self._properties['longest_task_waiting_sid'] - @property - def tasks_by_priority(self): - """ - :returns: The number of Tasks by priority - :rtype: dict - """ - return self._properties['tasks_by_priority'] +class WorkspaceRealTimeStatisticsList(ListResource): - @property - def tasks_by_status(self): - """ - :returns: The number of Tasks by their current status - :rtype: dict + def __init__(self, version: Version, workspace_sid: str): """ - return self._properties['tasks_by_status'] + Initialize the WorkspaceRealTimeStatisticsList - @property - def total_tasks(self): - """ - :returns: The total number of Tasks - :rtype: unicode - """ - return self._properties['total_tasks'] + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. - @property - def total_workers(self): - """ - :returns: The total number of Workers in the Workspace - :rtype: unicode """ - return self._properties['total_workers'] + super().__init__(version) - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace - :rtype: unicode - """ - return self._properties['workspace_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def url(self): + def get(self) -> WorkspaceRealTimeStatisticsContext: """ - :returns: The absolute URL of the Workspace statistics resource - :rtype: unicode - """ - return self._properties['url'] + Constructs a WorkspaceRealTimeStatisticsContext - def fetch(self, task_channel=values.unset): """ - Fetch the WorkspaceRealTimeStatisticsInstance + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) - :param unicode task_channel: Only calculate real-time statistics on this TaskChannel + def __call__(self) -> WorkspaceRealTimeStatisticsContext: + """ + Constructs a WorkspaceRealTimeStatisticsContext - :returns: The 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 7b5d5e9a47..b8414a5c6c 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -1,280 +1,282 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Workspace + :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 SID of the Workspace + 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 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, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: """ - Build an instance of WorkspaceStatisticsInstance + Fetch the WorkspaceStatisticsInstance - :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 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.WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance + :returns: The fetched WorkspaceStatisticsInstance """ - return WorkspaceStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution['workspace_sid'], + + 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 __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 WorkspaceStatisticsContext(InstanceContext): - """ """ + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) - def __init__(self, version, workspace_sid): + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: """ - Initialize the WorkspaceStatisticsContext + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance - :param Version version: Version that contains the resource - :param workspace_sid: The SID of the Workspace to fetch + :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 """ - super(WorkspaceStatisticsContext, self).__init__(version) - - # Path Solution - self._solution = {'workspace_sid': workspace_sid, } - self._uri = '/Workspaces/{workspace_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 the 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, + } + ) - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_channel: Only calculate statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + headers = values.of({}) - :returns: The fetched WorkspaceStatisticsInstance - :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsInstance - """ - data = values.of({ - 'Minutes': minutes, - 'StartDate': serialize.iso8601_datetime(start_date), - 'EndDate': serialize.iso8601_datetime(end_date), - 'TaskChannel': task_channel, - 'SplitByWaitTime': split_by_wait_time, - }) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri, params=data, ) + 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.get('realtime'), - 'cumulative': payload.get('cumulative'), - 'account_sid': payload.get('account_sid'), - 'workspace_sid': payload.get('workspace_sid'), - 'url': payload.get('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: n object that contains the real-time statistics for the Workspace - :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: An object that contains the cumulative statistics for the Workspace - :rtype: dict """ - return self._properties['cumulative'] + super().__init__(version) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } - @property - def workspace_sid(self): - """ - :returns: The SID of the Workspace - :rtype: unicode + def get(self) -> WorkspaceStatisticsContext: """ - return self._properties['workspace_sid'] + Constructs a WorkspaceStatisticsContext - @property - def url(self): - """ - :returns: The absolute URL of the Workspace statistics resource - :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 the WorkspaceStatisticsInstance - - :param unicode minutes: Only calculate statistics since this many minutes in the past - :param datetime start_date: Only calculate statistics from on or after this date - :param datetime end_date: Only calculate statistics from this date and time and earlier - :param unicode task_channel: Only calculate statistics on this TaskChannel. - :param unicode split_by_wait_time: A comma separated list of values that describes the thresholds to calculate statistics on + Constructs a WorkspaceStatisticsContext - :returns: The 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 32ef7cea96..14bd6be655 100644 --- a/twilio/rest/trunking/__init__.py +++ b/twilio/rest/trunking/__init__.py @@ -1,53 +1,15 @@ -# coding=utf-8 -r""" -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 6f28ed7a7e..af530b97c7 100644 --- a/twilio/rest/trunking/v1/__init__.py +++ b/twilio/rest/trunking/v1/__init__.py @@ -1,42 +1,43 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 5cfc5477ab..6a93a83233 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -1,625 +1,887 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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) - - # Path Solution - self._solution = {} - self._uri = '/Trunks'.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, domain_name=values.unset, - disaster_recovery_url=values.unset, - disaster_recovery_method=values.unset, recording=values.unset, - secure=values.unset, cnam_lookup_enabled=values.unset): + :returns: TrunkContext for this TrunkInstance """ - Create the TrunkInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic - :param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL - :param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url - :param TrunkInstance.RecordingSetting recording: The recording settings for the trunk - :param bool secure: Whether Secure Trunking is enabled for the trunk - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk + if self._context is None: + self._context = TrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + def delete(self) -> bool: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'DomainName': domain_name, - 'DisasterRecoveryUrl': disaster_recovery_url, - 'DisasterRecoveryMethod': disaster_recovery_method, - 'Recording': recording, - 'Secure': secure, - 'CnamLookupEnabled': cnam_lookup_enabled, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + 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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return TrunkPage(self._version, response, self._solution) - - def get_page(self, target_url): + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": """ - 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: - def get(self, sid): + :returns: The updated TrunkInstance """ - Constructs a TrunkContext + 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, + ) - :param sid: The unique string that identifies the resource + @property + def credentials_lists(self) -> CredentialListList: + """ + 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: + """ + Access the ip_access_control_lists """ - return TrunkContext(self._version, sid=sid, ) + 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 unique string that identifies the resource + @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: """ - return TrunkContext(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 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 - - def get_instance(self, payload): - """ - Build an instance of TrunkInstance + self._solution = { + "sid": sid, + } + self._uri = "/Trunks/{sid}".format(**self._solution) - :param dict payload: Payload response from the API + 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 - :returns: twilio.rest.trunking.v1.trunk.TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + def delete(self) -> bool: """ - return TrunkInstance(self._version, payload, ) + Deletes the TrunkInstance - 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 TrunkContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the TrunkContext + Asynchronous coroutine that deletes the TrunkInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.trunking.v1.trunk.TrunkContext - :rtype: twilio.rest.trunking.v1.trunk.TrunkContext + :returns: True if delete succeeds, False otherwise """ - super(TrunkContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Trunks/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._origination_urls = None - self._credentials_lists = None - self._ip_access_control_lists = None - self._phone_numbers = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> TrunkInstance: """ Fetch the TrunkInstance + :returns: The fetched TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def delete(self): + async def fetch_async(self) -> TrunkInstance: """ - Deletes the TrunkInstance + Asynchronous coroutine to fetch the TrunkInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched TrunkInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - 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, cnam_lookup_enabled=values.unset): + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: """ Update the TrunkInstance - :param unicode friendly_name: A string to describe the resource - :param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic - :param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL - :param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url - :param TrunkInstance.RecordingSetting recording: The recording settings for the trunk - :param bool secure: Whether Secure Trunking is enabled for the trunk - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk + :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 - :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, - 'CnamLookupEnabled': cnam_lookup_enabled, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return TrunkInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def origination_urls(self): - """ - Access the origination_urls + headers["Accept"] = "application/json" - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance """ - if self._origination_urls is None: - self._origination_urls = OriginationUrlList(self._version, trunk_sid=self._solution['sid'], ) - return self._origination_urls + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) @property - def credentials_lists(self): + 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): - """ """ - - class RecordingSetting(object): - DO_NOT_RECORD = "do-not-record" - RECORD_FROM_RINGING = "record-from-ringing" - RECORD_FROM_ANSWER = "record-from-answer" - - 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.get('account_sid'), - 'domain_name': payload.get('domain_name'), - 'disaster_recovery_method': payload.get('disaster_recovery_method'), - 'disaster_recovery_url': payload.get('disaster_recovery_url'), - 'friendly_name': payload.get('friendly_name'), - 'secure': payload.get('secure'), - 'recording': payload.get('recording'), - 'cnam_lookup_enabled': payload.get('cnam_lookup_enabled'), - 'auth_type': payload.get('auth_type'), - 'auth_type_set': payload.get('auth_type_set'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'sid': payload.get('sid'), - 'url': payload.get('url'), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def domain_name(self): - """ - :returns: The unique address you reserve on Twilio to which you route your SIP traffic - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['domain_name'] + return "" - @property - def disaster_recovery_method(self): - """ - :returns: The HTTP method we use to call the disaster_recovery_url - :rtype: unicode - """ - return self._properties['disaster_recovery_method'] - @property - def disaster_recovery_url(self): - """ - :returns: The HTTP URL that we call if an error occurs while sending SIP traffic towards your configured Origination URL - :rtype: unicode - """ - return self._properties['disaster_recovery_url'] +class TrunkList(ListResource): - @property - def friendly_name(self): + def __init__(self, version: Version): """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + Initialize the TrunkList - @property - def secure(self): - """ - :returns: Whether Secure Trunking is enabled for the trunk - :rtype: bool - """ - return self._properties['secure'] + :param version: Version that contains the resource - @property - def recording(self): - """ - :returns: The recording settings for the trunk - :rtype: dict """ - return self._properties['recording'] + super().__init__(version) - @property - def cnam_lookup_enabled(self): - """ - :returns: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :rtype: bool - """ - return self._properties['cnam_lookup_enabled'] + self._uri = "/Trunks" - @property - def auth_type(self): - """ - :returns: The types of authentication mapped to the domain - :rtype: unicode + 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: """ - return self._properties['auth_type'] + Create the TrunkInstance - @property - def auth_type_set(self): - """ - :returns: Reserved - :rtype: unicode - """ - return self._properties['auth_type_set'] + :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: - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + :returns: The created TrunkInstance """ - return self._properties['date_created'] - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronously create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance """ - return self._properties['date_updated'] - @property - def sid(self): + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrunkInstance]: """ - :returns: The unique string that identifies the resource - :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 absolute URL of the resource - :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 URLs of related resources - :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 the 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. - :returns: The fetched TrunkInstance - :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to 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._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" - 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, cnam_lookup_enabled=values.unset): + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrunkPage: """ - Update the TrunkInstance + Asynchronously retrieve a single page of TrunkInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource - :param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic - :param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL - :param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url - :param TrunkInstance.RecordingSetting recording: The recording settings for the trunk - :param bool secure: Whether Secure Trunking is enabled for the trunk - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 - :returns: The 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, - cnam_lookup_enabled=cnam_lookup_enabled, + 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 + + :param target_url: API-generated URL for the requested results page - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList + :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 - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList + :param target_url: API-generated URL for the requested results page + + :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 6ccf582406..09ffc99260 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -1,382 +1,538 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Trunk the credential list in associated with + :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 the CredentialListInstance - - :param unicode credential_list_sid: The SID of the Credential List that you want to associate with the trunk + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the CredentialListContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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({}) - def get(self, sid): + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: """ - Constructs a CredentialListContext + Asynchronous coroutine that deletes the CredentialListInstance - :param sid: The unique string that identifies the resource - :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 unique string that identifies the resource - :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 + ) + + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The SID of the Trunk the credential list in associated with + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage - :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage + :returns: Machine friendly representation """ - super(CredentialListPage, 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 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 SID of the Trunk from which to fetch the credential list - :param sid: The unique string that identifies the resource + :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 the CredentialListInstance + Create the CredentialListInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('account_sid'), - 'sid': payload.get('sid'), - 'trunk_sid': payload.get('trunk_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 SID of the Account that created the resource - :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 unique string that identifies the resource - :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 SID of the Trunk the credential list in associated with - :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 string that you assigned to describe the resource - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the resource - :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 the CredentialListInstance + Constructs a CredentialListContext - :returns: The 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 3ad0edaf72..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,382 +1,542 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Trunk the resource is associated with + :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 the IpAccessControlListInstance - - :param unicode ip_access_control_list_sid: The SID of the IP Access Control List that you want to associate with the trunk + return self._proxy.delete() - :returns: The 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(method='POST', uri=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']) - 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): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the IpAccessControlListContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 unique string that identifies the resource - :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 unique string that identifies the resource - :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 + ) + + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param trunk_sid: The SID of the Trunk the resource is associated with + def __repr__(self) -> str: + """ + Provide a friendly representation - :returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage - :rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListPage + :returns: Machine friendly representation """ - super(IpAccessControlListPage, 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 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 SID of the Trunk from which to fetch the IP Access Control List - :param sid: The unique string that identifies the resource + :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 the IpAccessControlListInstance + Create the IpAccessControlListInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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(method='DELETE', uri=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.get('account_sid'), - 'sid': payload.get('sid'), - 'trunk_sid': payload.get('trunk_sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 SID of the Account that created the resource - :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 unique string that identifies the resource - :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 SID of the Trunk the resource is associated with - :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 string that you assigned to describe the resource - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the resource - :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 the IpAccessControlListInstance + Constructs a IpAccessControlListContext - :returns: The 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 a8c48a6094..082fa34beb 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -1,483 +1,722 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Trunk that owns the Origination URL + 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 the OriginationUrlInstance + Deletes the OriginationUrlInstance - :param unicode weight: The value that determines the relative load the URI should receive compared to others with the same priority - :param unicode priority: The relative importance of the URI - :param bool enabled: Whether the URL is enabled - :param unicode friendly_name: A string to describe the resource - :param unicode sip_url: The SIP address you want Twilio to route your Origination calls to - :returns: The 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(method='POST', uri=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. - - :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.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']) + :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 """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return OriginationUrlPage(self._version, response, self._solution) + return self._proxy.update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) - 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 unique string that identifies the resource - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext +class OriginationUrlContext(InstanceContext): + + 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 unique string that identifies the resource + # 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 SID of the Trunk that owns the Origination URL - :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 + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def get_instance(self, payload): + def fetch(self) -> OriginationUrlInstance: """ - Build an instance of OriginationUrlInstance + Fetch the OriginationUrlInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance + :returns: The fetched OriginationUrlInstance """ - return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_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 OriginationUrlContext(InstanceContext): - """ """ + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) - def __init__(self, version, trunk_sid, sid): + async def fetch_async(self) -> OriginationUrlInstance: """ - Initialize the OriginationUrlContext + Asynchronous coroutine to fetch the OriginationUrlInstance - :param Version version: Version that contains the resource - :param trunk_sid: The SID of the Trunk from which to fetch the OriginationUrl - :param sid: The unique string that identifies the resource - :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext + :returns: The fetched OriginationUrlInstance """ - super(OriginationUrlContext, self).__init__(version) - # Path Solution - self._solution = {'trunk_sid': trunk_sid, 'sid': sid, } - self._uri = '/Trunks/{trunk_sid}/OriginationUrls/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the OriginationUrlInstance + headers["Accept"] = "application/json" - :returns: The fetched OriginationUrlInstance - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, weight=values.unset, priority=values.unset, - enabled=values.unset, friendly_name=values.unset, - sip_url=values.unset): + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: """ - Update the OriginationUrlInstance + Asynchronous coroutine to update the OriginationUrlInstance - :param unicode weight: The value that determines the relative load the URI should receive compared to others with the same priority - :param unicode priority: The relative importance of the URI - :param bool enabled: Whether the URL is enabled - :param unicode friendly_name: A string to describe the resource - :param unicode sip_url: The SIP address you want Twilio to route your Origination calls to + :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 - :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance """ - data = values.of({ - 'Weight': weight, - 'Priority': priority, - 'Enabled': enabled, - 'FriendlyName': friendly_name, - 'SipUrl': sip_url, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) return OriginationUrlInstance( self._version, payload, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + trunk_sid=self._solution["trunk_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 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.get('account_sid'), - 'sid': payload.get('sid'), - 'trunk_sid': payload.get('trunk_sid'), - 'weight': deserialize.integer(payload.get('weight')), - 'enabled': payload.get('enabled'), - 'sip_url': payload.get('sip_url'), - 'friendly_name': payload.get('friendly_name'), - 'priority': deserialize.integer(payload.get('priority')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('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 SID of the Account that created the resource - :rtype: unicode + def __repr__(self) -> str: """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def sid(self): + :returns: Machine friendly representation """ - :returns: The unique string that identifies the resource - :rtype: unicode + return "" + + +class OriginationUrlList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): """ - return self._properties['sid'] + 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 trunk_sid(self): """ - :returns: The SID of the Trunk that owns the Origination URL - :rtype: unicode + 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: """ - return self._properties['trunk_sid'] + Create the OriginationUrlInstance - @property - def weight(self): + :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 """ - :returns: The value that determines the relative load the URI should receive compared to others with the same priority - :rtype: unicode + + 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: """ - return self._properties['weight'] + Asynchronously create the OriginationUrlInstance - @property - def enabled(self): + :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 """ - :returns: Whether the URL is enabled - :rtype: bool + + 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 address you want Twilio to route your Origination calls 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[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 string that you assigned to describe the 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[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 relative importance of the URI - :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 absolute URL of the 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 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 the OriginationUrlInstance + response = self._version.domain.twilio.request("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) - :returns: The 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 value that determines the relative load the URI should receive compared to others with the same priority - :param unicode priority: The relative importance of the URI - :param bool enabled: Whether the URL is enabled - :param unicode friendly_name: A string to describe the resource - :param unicode sip_url: The SIP address you want Twilio to route your Origination calls to + def __call__(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext - :returns: The 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 40e511c6fa..a7c3dbe20d 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -1,559 +1,589 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 SID of the Trunk that handles calls to the phone number + """ + :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 the PhoneNumberInstance + Deletes the PhoneNumberInstance - :param unicode phone_number_sid: The SID of the Incoming Phone Number that you want to associate with the trunk - :returns: The created PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'PhoneNumberSid': phone_number_sid, }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance - return PhoneNumberInstance(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 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. + 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.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']) + :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.trunking.v1.trunk.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 __repr__(self) -> str: """ - Retrieve a single page of PhoneNumberInstance records from the API. - Request is executed immediately + Provide a friendly representation - :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 PhoneNumberInstance - :rtype: twilio.rest.trunking.v1.trunk.phone_number.PhoneNumberPage + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the PhoneNumberContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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 unique string that identifies the resource - :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 unique string that identifies the resource - :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 SID of the Trunk that handles calls to the phone number + 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 + + :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 PhoneNumberPage(Page): + + 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 SID of the Trunk from which to fetch the PhoneNumber resource - :param sid: The unique string that identifies the resource + :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 the PhoneNumberInstance + Create the PhoneNumberInstance - :returns: The 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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return PhoneNumberInstance( - self._version, - payload, - trunk_sid=self._solution['trunk_sid'], - sid=self._solution['sid'], + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def delete(self): - """ - Deletes the PhoneNumberInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) - 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 [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 """ - 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.get('account_sid'), - 'address_requirements': payload.get('address_requirements'), - 'api_version': payload.get('api_version'), - 'beta': payload.get('beta'), - 'capabilities': payload.get('capabilities'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'links': payload.get('links'), - 'phone_number': payload.get('phone_number'), - 'sid': payload.get('sid'), - 'sms_application_sid': payload.get('sms_application_sid'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'trunk_sid': payload.get('trunk_sid'), - 'url': payload.get('url'), - 'voice_application_sid': payload.get('voice_application_sid'), - 'voice_caller_id_lookup': payload.get('voice_caller_id_lookup'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('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 SID of the Account that created the resource - :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: Whether the phone number requires an Address registered with Twilio - :rtype: PhoneNumberInstance.AddressRequirement - """ - return self._properties['address_requirements'] + return self._version.stream(page, limits["limit"]) - @property - def api_version(self): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: """ - :returns: The API version used to start a new TwiML session - :rtype: unicode - """ - 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: Whether the phone number is new to the Twilio platform - :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: Indicate if a phone can receive calls or messages - :rtype: dict + :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 RFC 2822 date and time in GMT when the resource was 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 RFC 2822 date and time in GMT when the resource was last 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 string that you assigned to describe the resource - :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 URLs of related resources - :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 in E.164 format - :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 unique string that identifies the resource - :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 SID of the application that handles SMS messages sent to the phone number - :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): - """ - :returns: The HTTP method used with sms_fallback_url - :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, + ) -> PhoneNumberPage: """ - 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 URL that we call when an error occurs while retrieving or executing the TwiML - :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 HTTP method to use with sms_url - :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 URL we call when the phone number receives an incoming SMS message - :rtype: unicode - """ - return self._properties['sms_url'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def status_callback(self): - """ - :returns: The URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + headers["Accept"] = "application/json" - @property - def status_callback_method(self): - """ - :returns: The HTTP method we use to call status_callback - :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): + async def 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 SID of the Trunk that handles calls to the phone number - :rtype: unicode - """ - 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 absolute URL of the resource - :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 SID of the application that handles calls to the phone number - :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: Whether to lookup the caller's name - :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 HTTP method that we use to call voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] + headers["Accept"] = "application/json" - @property - def voice_fallback_url(self): - """ - :returns: The URL we call when an error occurs in TwiML - :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 HTTP method used with the voice_url - :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 URL we call when the phone number receives a call - :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 the PhoneNumberInstance + Constructs a PhoneNumberContext - :returns: The 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 index c167559a77..a66b3333b0 100644 --- a/twilio/rest/verify/__init__.py +++ b/twilio/rest/verify/__init__.py @@ -1,60 +1,67 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.verify.v2 import V2 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Verify Domain - - :returns: Domain for Verify - :rtype: twilio.rest.verify.Verify - """ - super(Verify, self).__init__(twilio) - - self.base_url = 'https://verify.twilio.com' - - # Versions - self._v2 = None - +class Verify(VerifyBase): @property - def v2(self): - """ - :returns: Version v2 of verify - :rtype: twilio.rest.verify.v2.V2 - """ - if self._v2 is None: - self._v2 = V2(self) - return self._v2 + def forms(self) -> FormList: + warn( + "forms is deprecated. Use v2.forms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.forms @property - def forms(self): - """ - :rtype: twilio.rest.verify.v2.form.FormList - """ - return self.v2.forms + def safelist(self) -> SafelistList: + warn( + "safelist is deprecated. Use v2.safelist instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.safelist @property - def services(self): - """ - :rtype: twilio.rest.verify.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 + @property + def verification_attempts(self) -> VerificationAttemptList: + warn( + "verification_attempts is deprecated. Use v2.verification_attempts instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.verification_attempts - :returns: Machine friendly representation - :rtype: str - """ - return '' + @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 index ddc2ccef59..01bee13b0d 100644 --- a/twilio/rest/verify/v2/__init__.py +++ b/twilio/rest/verify/v2/__init__.py @@ -1,53 +1,87 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Verify - :returns: V2 version of Verify - :rtype: twilio.rest.verify.v2.V2.V2 + :param domain: The Twilio.verify domain """ - super(V2, self).__init__(domain) - self.version = 'v2' - self._forms = None - self._services = None + 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): - """ - :rtype: twilio.rest.verify.v2.form.FormList - """ + def forms(self) -> FormList: if self._forms is None: self._forms = FormList(self) return self._forms @property - def services(self): - """ - :rtype: twilio.rest.verify.v2.service.ServiceList - """ + 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 - def __repr__(self): + @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 - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/verify/v2/form.py b/twilio/rest/verify/v2/form.py index 1a50a39b96..454030208d 100644 --- a/twilio/rest/verify/v2/form.py +++ b/twilio/rest/verify/v2/form.py @@ -1,242 +1,198 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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.page import Page +from twilio.base.version import Version -class FormList(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 FormInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the FormList + class FormTypes(object): + FORM_PUSH = "form-push" - :param Version version: Version that contains the resource + """ + :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 - :returns: twilio.rest.verify.v2.form.FormList - :rtype: twilio.rest.verify.v2.form.FormList + @property + def _proxy(self) -> "FormContext": """ - super(FormList, 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 = {} + :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 get(self, form_type): + def fetch(self) -> "FormInstance": """ - Constructs a FormContext + Fetch the FormInstance - :param form_type: The Type of this Form - :returns: twilio.rest.verify.v2.form.FormContext - :rtype: twilio.rest.verify.v2.form.FormContext + :returns: The fetched FormInstance """ - return FormContext(self._version, form_type=form_type, ) + return self._proxy.fetch() - def __call__(self, form_type): + async def fetch_async(self) -> "FormInstance": """ - Constructs a FormContext + Asynchronous coroutine to fetch the FormInstance - :param form_type: The Type of this Form - :returns: twilio.rest.verify.v2.form.FormContext - :rtype: twilio.rest.verify.v2.form.FormContext + :returns: The fetched FormInstance """ - return FormContext(self._version, form_type=form_type, ) + 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 FormPage(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 FormContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): """ - Initialize the FormPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the FormContext - :returns: twilio.rest.verify.v2.form.FormPage - :rtype: twilio.rest.verify.v2.form.FormPage + :param version: Version that contains the resource + :param form_type: The Type of this Form. Currently only `form-push` is supported. """ - super(FormPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "form_type": form_type, + } + self._uri = "/Forms/{form_type}".format(**self._solution) - def get_instance(self, payload): + def fetch(self) -> FormInstance: """ - Build an instance of FormInstance + Fetch the FormInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.form.FormInstance - :rtype: twilio.rest.verify.v2.form.FormInstance + :returns: The fetched FormInstance """ - return FormInstance(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 FormContext(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 FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) - def __init__(self, version, form_type): + async def fetch_async(self) -> FormInstance: """ - Initialize the FormContext + Asynchronous coroutine to fetch the FormInstance - :param Version version: Version that contains the resource - :param form_type: The Type of this Form - :returns: twilio.rest.verify.v2.form.FormContext - :rtype: twilio.rest.verify.v2.form.FormContext + :returns: The fetched FormInstance """ - super(FormContext, self).__init__(version) - # Path Solution - self._solution = {'form_type': form_type, } - self._uri = '/Forms/{form_type}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the FormInstance + headers["Accept"] = "application/json" - :returns: The fetched FormInstance - :rtype: twilio.rest.verify.v2.form.FormInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - return FormInstance(self._version, payload, form_type=self._solution['form_type'], ) + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) - 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 FormInstance(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. """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - class FormTypes(object): - FORM_PUSH = "form-push" - - def __init__(self, version, payload, form_type=None): - """ - Initialize the FormInstance - :returns: twilio.rest.verify.v2.form.FormInstance - :rtype: twilio.rest.verify.v2.form.FormInstance - """ - super(FormInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'form_type': payload.get('form_type'), - 'forms': payload.get('forms'), - 'form_meta': payload.get('form_meta'), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'form_type': form_type or self._properties['form_type'], } +class FormList(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 - - :returns: FormContext for this FormInstance - :rtype: twilio.rest.verify.v2.form.FormContext - """ - if self._context is None: - self._context = FormContext(self._version, form_type=self._solution['form_type'], ) - return self._context + Initialize the FormList - @property - def form_type(self): - """ - :returns: The Type of this Form - :rtype: FormInstance.FormTypes - """ - return self._properties['form_type'] + :param version: Version that contains the resource - @property - def forms(self): - """ - :returns: Object that contains the available forms for this type. - :rtype: dict """ - return self._properties['forms'] + super().__init__(version) - @property - def form_meta(self): - """ - :returns: Additional information for the available forms for this type. - :rtype: dict + def get(self, form_type: "FormInstance.FormTypes") -> FormContext: """ - return self._properties['form_meta'] + Constructs a FormContext - @property - def url(self): - """ - :returns: The URL to access the forms for this type. - :rtype: unicode + :param form_type: The Type of this Form. Currently only `form-push` is supported. """ - return self._properties['url'] + return FormContext(self._version, form_type=form_type) - def fetch(self): + def __call__(self, form_type: "FormInstance.FormTypes") -> FormContext: """ - Fetch the FormInstance + Constructs a FormContext - :returns: The fetched FormInstance - :rtype: twilio.rest.verify.v2.form.FormInstance + :param form_type: The Type of this Form. Currently only `form-push` is supported. """ - return self._proxy.fetch() + return FormContext(self._version, form_type=form_type) - 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/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 index 3e5664dad5..a64ab7a552 100644 --- a/twilio/rest/verify/v2/service/__init__.py +++ b/twilio/rest/verify/v2/service/__init__.py @@ -1,723 +1,1157 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.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.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 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 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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None - :returns: twilio.rest.verify.v2.service.ServiceList - :rtype: twilio.rest.verify.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, code_length=values.unset, - lookup_enabled=values.unset, skip_sms_to_landlines=values.unset, - dtmf_input_required=values.unset, tts_name=values.unset, - psd2_enabled=values.unset, do_not_share_warning_enabled=values.unset, - custom_code_enabled=values.unset, push=values.unset): + :returns: ServiceContext for this ServiceInstance """ - Create the ServiceInstance - - :param unicode friendly_name: A string to describe the verification service - :param unicode code_length: The length of the verification code to generate - :param bool lookup_enabled: Whether to perform a lookup with each verification - :param bool skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines - :param bool dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call - :param unicode tts_name: The name of an alternative text-to-speech service to use in phone calls - :param bool psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification - :param bool do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS. - :param bool custom_code_enabled: Whether to allow sending verifications with a custom code. - :param dict push: Optional service level push factors configuration + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + def delete(self) -> bool: """ - data = values.of({ - 'FriendlyName': friendly_name, - 'CodeLength': code_length, - 'LookupEnabled': lookup_enabled, - 'SkipSmsToLandlines': skip_sms_to_landlines, - 'DtmfInputRequired': dtmf_input_required, - 'TtsName': tts_name, - 'Psd2Enabled': psd2_enabled, - 'DoNotShareWarningEnabled': do_not_share_warning_enabled, - 'CustomCodeEnabled': custom_code_enabled, - 'Push': serialize.object(push), - }) - - payload = self._version.create(method='POST', uri=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.verify.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']) + :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.verify.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": """ - 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.verify.v2.service.ServicePage + :returns: The fetched ServiceInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return ServicePage(self._version, response, self._solution) + :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 - def get_page(self, target_url): + :returns: The updated ServiceInstance """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServicePage + :returns: The updated ServiceInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ServicePage(self._version, response, self._solution) + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + return self._proxy.access_tokens - def get(self, sid): + @property + def entities(self) -> EntityList: """ - Constructs a ServiceContext + Access the entities + """ + return self._proxy.entities - :param sid: The unique string that identifies the resource + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + return self._proxy.messaging_configurations - :returns: twilio.rest.verify.v2.service.ServiceContext - :rtype: twilio.rest.verify.v2.service.ServiceContext + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits """ - return ServiceContext(self._version, sid=sid, ) + return self._proxy.rate_limits - def __call__(self, sid): + @property + def verifications(self) -> VerificationList: """ - Constructs a ServiceContext + Access the verifications + """ + return self._proxy.verifications - :param sid: The unique string that identifies the resource + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + return self._proxy.verification_checks - :returns: twilio.rest.verify.v2.service.ServiceContext - :rtype: twilio.rest.verify.v2.service.ServiceContext + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks """ - return ServiceContext(self._version, sid=sid, ) + 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 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.verify.v2.service.ServicePage - :rtype: twilio.rest.verify.v2.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 - - 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._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 - :returns: twilio.rest.verify.v2.service.ServiceInstance - :rtype: twilio.rest.verify.v2.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): - """ """ + 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 unique string that identifies the resource - :returns: twilio.rest.verify.v2.service.ServiceContext - :rtype: twilio.rest.verify.v2.service.ServiceContext + :returns: True if delete succeeds, False otherwise """ - super(ServiceContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Services/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._verifications = None - self._verification_checks = None - self._rate_limits = None - self._messaging_configurations = None - self._entities = None - self._webhooks = None - self._access_tokens = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> ServiceInstance: """ Fetch the ServiceInstance + :returns: The fetched ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): + 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: """ - Deletes the ServiceInstance + Asynchronous coroutine to fetch the ServiceInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + + :returns: The fetched ServiceInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def update(self, friendly_name=values.unset, code_length=values.unset, - lookup_enabled=values.unset, skip_sms_to_landlines=values.unset, - dtmf_input_required=values.unset, tts_name=values.unset, - psd2_enabled=values.unset, do_not_share_warning_enabled=values.unset, - custom_code_enabled=values.unset, push=values.unset): + 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 unicode friendly_name: A string to describe the verification service - :param unicode code_length: The length of the verification code to generate - :param bool lookup_enabled: Whether to perform a lookup with each verification - :param bool skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines - :param bool dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call - :param unicode tts_name: The name of an alternative text-to-speech service to use in phone calls - :param bool psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification - :param bool do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. - :param bool custom_code_enabled: Whether to allow sending verifications with a custom code. - :param dict push: Optional service level push factors configuration + :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 - :rtype: twilio.rest.verify.v2.service.ServiceInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'CodeLength': code_length, - 'LookupEnabled': lookup_enabled, - 'SkipSmsToLandlines': skip_sms_to_landlines, - 'DtmfInputRequired': dtmf_input_required, - 'TtsName': tts_name, - 'Psd2Enabled': psd2_enabled, - 'DoNotShareWarningEnabled': do_not_share_warning_enabled, - 'CustomCodeEnabled': custom_code_enabled, - 'Push': serialize.object(push), - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return ServiceInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def verifications(self): - """ - Access the verifications + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList + 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 """ - if self._verifications is None: - self._verifications = VerificationList(self._version, service_sid=self._solution['sid'], ) - return self._verifications + + 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 verification_checks(self): + def access_tokens(self) -> AccessTokenList: """ - Access the verification_checks - - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList + Access the access_tokens """ - if self._verification_checks is None: - self._verification_checks = VerificationCheckList(self._version, service_sid=self._solution['sid'], ) - return self._verification_checks + if self._access_tokens is None: + self._access_tokens = AccessTokenList( + self._version, + self._solution["sid"], + ) + return self._access_tokens @property - def rate_limits(self): + def entities(self) -> EntityList: """ - Access the rate_limits - - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + Access the entities """ - if self._rate_limits is None: - self._rate_limits = RateLimitList(self._version, service_sid=self._solution['sid'], ) - return self._rate_limits + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities @property - def messaging_configurations(self): + def messaging_configurations(self) -> MessagingConfigurationList: """ Access the messaging_configurations - - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList """ if self._messaging_configurations is None: self._messaging_configurations = MessagingConfigurationList( self._version, - service_sid=self._solution['sid'], + self._solution["sid"], ) return self._messaging_configurations @property - def entities(self): + def rate_limits(self) -> RateLimitList: """ - Access the entities - - :returns: twilio.rest.verify.v2.service.entity.EntityList - :rtype: twilio.rest.verify.v2.service.entity.EntityList + Access the rate_limits """ - if self._entities is None: - self._entities = EntityList(self._version, service_sid=self._solution['sid'], ) - return self._entities + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits @property - def webhooks(self): + def verifications(self) -> VerificationList: """ - Access the webhooks - - :returns: twilio.rest.verify.v2.service.webhook.WebhookList - :rtype: twilio.rest.verify.v2.service.webhook.WebhookList + Access the verifications """ - if self._webhooks is None: - self._webhooks = WebhookList(self._version, service_sid=self._solution['sid'], ) - return self._webhooks + if self._verifications is None: + self._verifications = VerificationList( + self._version, + self._solution["sid"], + ) + return self._verifications @property - def access_tokens(self): + def verification_checks(self) -> VerificationCheckList: """ - Access the access_tokens + Access the verification_checks + """ + if self._verification_checks is None: + self._verification_checks = VerificationCheckList( + self._version, + self._solution["sid"], + ) + return self._verification_checks - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenList - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenList + @property + def webhooks(self) -> WebhookList: """ - if self._access_tokens is None: - self._access_tokens = AccessTokenList(self._version, service_sid=self._solution['sid'], ) - return self._access_tokens + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + 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) - + 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.verify.v2.service.ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance - """ - super(ServiceInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'code_length': deserialize.integer(payload.get('code_length')), - 'lookup_enabled': payload.get('lookup_enabled'), - 'psd2_enabled': payload.get('psd2_enabled'), - 'skip_sms_to_landlines': payload.get('skip_sms_to_landlines'), - 'dtmf_input_required': payload.get('dtmf_input_required'), - 'tts_name': payload.get('tts_name'), - 'do_not_share_warning_enabled': payload.get('do_not_share_warning_enabled'), - 'custom_code_enabled': payload.get('custom_code_enabled'), - 'push': payload.get('push'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('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.verify.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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + Provide a friendly representation - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['account_sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the verification service - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def code_length(self): - """ - :returns: The length of the verification code - :rtype: unicode - """ - return self._properties['code_length'] +class ServiceList(ListResource): - @property - def lookup_enabled(self): - """ - :returns: Whether to perform a lookup with each verification - :rtype: bool + def __init__(self, version: Version): """ - return self._properties['lookup_enabled'] + Initialize the ServiceList - @property - def psd2_enabled(self): - """ - :returns: Whether to pass PSD2 transaction parameters when starting a verification - :rtype: bool + :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: """ - return self._properties['psd2_enabled'] + Create the ServiceInstance - @property - def skip_sms_to_landlines(self): - """ - :returns: Whether to skip sending SMS verifications to landlines - :rtype: bool - """ - return self._properties['skip_sms_to_landlines'] + :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 - @property - def dtmf_input_required(self): - """ - :returns: Whether to ask the user to press a number before delivering the verify code in a phone call - :rtype: bool + :returns: The created ServiceInstance """ - return self._properties['dtmf_input_required'] - @property - def tts_name(self): - """ - :returns: The name of an alternative text-to-speech service to use in phone calls - :rtype: unicode - """ - return self._properties['tts_name'] + 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"}) - @property - def do_not_share_warning_enabled(self): - """ - :returns: Whether to add a security warning at the end of an SMS. - :rtype: bool - """ - return self._properties['do_not_share_warning_enabled'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def custom_code_enabled(self): - """ - :returns: Whether to allow sending verifications with a custom code. - :rtype: bool - """ - return self._properties['custom_code_enabled'] + headers["Accept"] = "application/json" - @property - def push(self): - """ - :returns: The service level configuration of factor push type. - :rtype: dict - """ - return self._properties['push'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + 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 - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + :returns: The created ServiceInstance """ - return self._properties['date_updated'] - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + 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"}) - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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.fetch() + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + 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[ServiceInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt 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(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) - def update(self, friendly_name=values.unset, code_length=values.unset, - lookup_enabled=values.unset, skip_sms_to_landlines=values.unset, - dtmf_input_required=values.unset, tts_name=values.unset, - psd2_enabled=values.unset, do_not_share_warning_enabled=values.unset, - custom_code_enabled=values.unset, push=values.unset): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - Update the 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 unicode friendly_name: A string to describe the verification service - :param unicode code_length: The length of the verification code to generate - :param bool lookup_enabled: Whether to perform a lookup with each verification - :param bool skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines - :param bool dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call - :param unicode tts_name: The name of an alternative text-to-speech service to use in phone calls - :param bool psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification - :param bool do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. - :param bool custom_code_enabled: Whether to allow sending verifications with a custom code. - :param dict push: Optional service level push factors configuration + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: The updated ServiceInstance - :rtype: twilio.rest.verify.v2.service.ServiceInstance + :returns: list that will contain up to limit results """ - 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=push, + return list( + self.stream( + limit=limit, + page_size=page_size, + ) ) - @property - def verifications(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: """ - Access the verifications + 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: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList + :returns: list that will contain up to limit results """ - return self._proxy.verifications + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def verification_checks(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, + ) -> ServicePage: """ - Access the verification_checks + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList + :param page_token: PageToken provided by the API + :param page_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.verification_checks + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def rate_limits(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: """ - Access the rate_limits + 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: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + :returns: Page of ServiceInstance """ - return self._proxy.rate_limits + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def messaging_configurations(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 messaging_configurations + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.messaging_configurations + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) - @property - def entities(self): + async def get_page_async(self, target_url: str) -> ServicePage: """ - Access the entities + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately - :returns: twilio.rest.verify.v2.service.entity.EntityList - :rtype: twilio.rest.verify.v2.service.entity.EntityList + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance """ - return self._proxy.entities + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) - @property - def webhooks(self): + def get(self, sid: str) -> ServiceContext: """ - Access the webhooks + Constructs a ServiceContext - :returns: twilio.rest.verify.v2.service.webhook.WebhookList - :rtype: twilio.rest.verify.v2.service.webhook.WebhookList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.webhooks + return ServiceContext(self._version, sid=sid) - @property - def access_tokens(self): + def __call__(self, sid: str) -> ServiceContext: """ - Access the access_tokens + Constructs a ServiceContext - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenList - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenList + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. """ - return self._proxy.access_tokens + 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/verify/v2/service/access_token.py b/twilio/rest/verify/v2/service/access_token.py index c8f9019ec2..45a0094e52 100644 --- a/twilio/rest/verify/v2/service/access_token.py +++ b/twilio/rest/verify/v2/service/access_token.py @@ -1,143 +1,315 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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_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 AccessTokenList(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 AccessTokenInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the AccessTokenList + class FactorTypes(object): + PUSH = "push" - :param Version version: Version that contains the resource - :param service_sid: The unique string that identifies the resource + """ + :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 - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenList - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenList + @property + def _proxy(self) -> "AccessTokenContext": """ - super(AccessTokenList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/AccessTokens'.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, factor_type): + :returns: AccessTokenContext for this AccessTokenInstance """ - Create the 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 - :param unicode identity: Unique external identifier of the Entity - :param AccessTokenInstance.FactorTypes factor_type: The Type of this Factor - :returns: The created AccessTokenInstance - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenInstance + :returns: The fetched AccessTokenInstance """ - data = values.of({'Identity': identity, 'FactorType': factor_type, }) + return self._proxy.fetch() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def fetch_async(self) -> "AccessTokenInstance": + """ + Asynchronous coroutine to fetch the AccessTokenInstance - return AccessTokenInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + :returns: The fetched AccessTokenInstance + """ + return await self._proxy.fetch_async() + + 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 AccessTokenPage(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 AccessTokenContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the AccessTokenPage + Initialize the AccessTokenContext - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The unique string that identifies the resource - - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenPage - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenPage + :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(AccessTokenPage, 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}/AccessTokens/{sid}".format( + **self._solution + ) + + def fetch(self) -> AccessTokenInstance: + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ - def get_instance(self, payload): + 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: """ - Build an instance of AccessTokenInstance + Asynchronous coroutine to fetch the AccessTokenInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenInstance - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenInstance + :returns: The fetched AccessTokenInstance """ - return AccessTokenInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def __repr__(self): + 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 - :rtype: str """ - return '' + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) -class AccessTokenInstance(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 AccessTokenList(ListResource): - class FactorTypes(object): - PUSH = "push" + 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. - def __init__(self, version, payload, service_sid): """ - Initialize the AccessTokenInstance + super().__init__(version) - :returns: twilio.rest.verify.v2.service.access_token.AccessTokenInstance - :rtype: twilio.rest.verify.v2.service.access_token.AccessTokenInstance + # 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: """ - super(AccessTokenInstance, self).__init__(version) + Create the AccessTokenInstance - # Marshaled Properties - self._properties = {'token': payload.get('token'), } + :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. - # Context - self._context = None - self._solution = {'service_sid': service_sid, } + :returns: The created AccessTokenInstance + """ - @property - def token(self): + 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: """ - :returns: Generated access token. - :rtype: unicode + 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 self._properties['token'] + return AccessTokenContext( + 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 """ - return '' + return "" diff --git a/twilio/rest/verify/v2/service/entity/__init__.py b/twilio/rest/verify/v2/service/entity/__init__.py index 3f55489b07..fa4bc1df12 100644 --- a/twilio/rest/verify/v2/service/entity/__init__.py +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -1,475 +1,609 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.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 EntityList(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 EntityList +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") - :param Version version: Version that contains the resource - :param service_sid: Service Sid. + self._solution = { + "service_sid": service_sid, + "identity": identity or self.identity, + } + self._context: Optional[EntityContext] = None - :returns: twilio.rest.verify.v2.service.entity.EntityList - :rtype: twilio.rest.verify.v2.service.entity.EntityList + @property + def _proxy(self) -> "EntityContext": """ - super(EntityList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Entities'.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, twilio_sandbox_mode=values.unset): + :returns: EntityContext for this EntityInstance """ - Create the EntityInstance - - :param unicode identity: Unique external identifier of the Entity - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + if self._context is None: + self._context = EntityContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return self._context - :returns: The created EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityInstance + def delete(self) -> bool: """ - data = values.of({'Identity': identity, }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + Deletes the EntityInstance - return EntityInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def stream(self, twilio_sandbox_mode=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.EntityInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the EntityInstance - page = self.page(twilio_sandbox_mode=twilio_sandbox_mode, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, twilio_sandbox_mode=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the EntityInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.EntityInstance] + :returns: The fetched EntityInstance """ - return list(self.stream(twilio_sandbox_mode=twilio_sandbox_mode, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, twilio_sandbox_mode=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "EntityInstance": """ - Retrieve a single page of EntityInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the EntityInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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 EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityPage + :returns: The fetched EntityInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) - - return EntityPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + @property + def challenges(self) -> ChallengeList: """ - Retrieve a specific page of EntityInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityPage + Access the challenges """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return EntityPage(self._version, response, self._solution) + return self._proxy.challenges - def get(self, identity): + @property + def factors(self) -> FactorList: """ - Constructs a EntityContext - - :param identity: Unique external identifier of the Entity - - :returns: twilio.rest.verify.v2.service.entity.EntityContext - :rtype: twilio.rest.verify.v2.service.entity.EntityContext + Access the factors """ - return EntityContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) + return self._proxy.factors - def __call__(self, identity): + @property + def new_factors(self) -> NewFactorList: """ - Constructs a EntityContext - - :param identity: Unique external identifier of the Entity - - :returns: twilio.rest.verify.v2.service.entity.EntityContext - :rtype: twilio.rest.verify.v2.service.entity.EntityContext + Access the new_factors """ - return EntityContext(self._version, service_sid=self._solution['service_sid'], identity=identity, ) + return self._proxy.new_factors - 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 EntityPage(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 EntityContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, identity: str): """ - Initialize the EntityPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. + Initialize the EntityContext - :returns: twilio.rest.verify.v2.service.entity.EntityPage - :rtype: twilio.rest.verify.v2.service.entity.EntityPage + :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(EntityPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of EntityInstance + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}".format( + **self._solution + ) - :param dict payload: Payload response from the API + self._challenges: Optional[ChallengeList] = None + self._factors: Optional[FactorList] = None + self._new_factors: Optional[NewFactorList] = None - :returns: twilio.rest.verify.v2.service.entity.EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityInstance + def delete(self) -> bool: """ - return EntityInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + Deletes the EntityInstance - 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 EntityContext(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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, service_sid, identity): + async def delete_async(self) -> bool: """ - Initialize the EntityContext + Asynchronous coroutine that deletes the EntityInstance - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity - :returns: twilio.rest.verify.v2.service.entity.EntityContext - :rtype: twilio.rest.verify.v2.service.entity.EntityContext + :returns: True if delete succeeds, False otherwise """ - super(EntityContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, } - self._uri = '/Services/{service_sid}/Entities/{identity}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._factors = None - self._challenges = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def delete(self, twilio_sandbox_mode=values.unset): + def fetch(self) -> EntityInstance: """ - Deletes the EntityInstance + Fetch the EntityInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: The fetched EntityInstance """ - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - def fetch(self, twilio_sandbox_mode=values.unset): + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> EntityInstance: """ - Fetch the EntityInstance + Asynchronous coroutine to fetch the EntityInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header :returns: The fetched EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityInstance """ - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) + 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'], + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], ) @property - def factors(self): + def challenges(self) -> ChallengeList: """ - Access the factors + Access the challenges + """ + if self._challenges is None: + self._challenges = ChallengeList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._challenges - :returns: twilio.rest.verify.v2.service.entity.factor.FactorList - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorList + @property + def factors(self) -> FactorList: + """ + Access the factors """ if self._factors is None: self._factors = FactorList( self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], + self._solution["service_sid"], + self._solution["identity"], ) return self._factors @property - def challenges(self): + def new_factors(self) -> NewFactorList: """ - Access the challenges - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeList - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeList + Access the new_factors """ - if self._challenges is None: - self._challenges = ChallengeList( + if self._new_factors is None: + self._new_factors = NewFactorList( self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], + self._solution["service_sid"], + self._solution["identity"], ) - return self._challenges + return self._new_factors - 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 EntityInstance(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 EntityPage(Page): - def __init__(self, version, payload, service_sid, identity=None): + def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: """ - Initialize the EntityInstance + Build an instance of EntityInstance - :returns: twilio.rest.verify.v2.service.entity.EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityInstance + :param payload: Payload response from the API """ - super(EntityInstance, self).__init__(version) + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'identity': payload.get('identity'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'identity': identity or self._properties['identity'], } - @property - def _proxy(self): +class EntityList(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 EntityList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. - :returns: EntityContext for this EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityContext """ - if self._context is None: - self._context = EntityContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - return self._context + super().__init__(version) - @property - def sid(self): + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Entities".format(**self._solution) + + def create(self, identity: str) -> EntityInstance: """ - :returns: A string that uniquely identifies this Entity. - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def identity(self): + 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: """ - :returns: Unique external identifier of the Entity - :rtype: unicode + 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 """ - return self._properties['identity'] - @property - def account_sid(self): + 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]: """ - :returns: Account Sid. - :rtype: unicode + 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 """ - return self._properties['account_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def service_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EntityInstance]: """ - :returns: Service Sid. - :rtype: unicode + 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 """ - 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[EntityInstance]: """ - :returns: The date this Entity was created - :rtype: datetime + 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 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[EntityInstance]: """ - :returns: The date this Entity was updated - :rtype: datetime + 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 self._properties['date_updated'] + 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, + ) -> EntityPage: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - 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 = 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: """ - :returns: Nested resource URLs. - :rtype: unicode + 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 """ - 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, self._solution) - def delete(self, twilio_sandbox_mode=values.unset): + def get_page(self, target_url: str) -> EntityPage: """ - Deletes the EntityInstance + Retrieve a specific page of EntityInstance records from the API. + Request is executed immediately - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of EntityInstance """ - return self._proxy.delete(twilio_sandbox_mode=twilio_sandbox_mode, ) + response = self._version.domain.twilio.request("GET", target_url) + return EntityPage(self._version, response, self._solution) - def fetch(self, twilio_sandbox_mode=values.unset): + async def get_page_async(self, target_url: str) -> EntityPage: """ - Fetch the EntityInstance + Asynchronously retrieve a specific page of EntityInstance records from the API. + Request is executed immediately - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The fetched EntityInstance - :rtype: twilio.rest.verify.v2.service.entity.EntityInstance + :returns: Page of EntityInstance """ - return self._proxy.fetch(twilio_sandbox_mode=twilio_sandbox_mode, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return EntityPage(self._version, response, self._solution) - @property - def factors(self): + def get(self, identity: str) -> EntityContext: """ - Access the factors + Constructs a EntityContext - :returns: twilio.rest.verify.v2.service.entity.factor.FactorList - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorList + :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 self._proxy.factors + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) - @property - def challenges(self): + def __call__(self, identity: str) -> EntityContext: """ - Access the challenges + Constructs a EntityContext - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeList - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeList + :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 self._proxy.challenges + return EntityContext( + self._version, service_sid=self._solution["service_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/verify/v2/service/entity/challenge.py b/twilio/rest/verify/v2/service/entity/challenge.py deleted file mode 100644 index fd82f2f622..0000000000 --- a/twilio/rest/verify/v2/service/entity/challenge.py +++ /dev/null @@ -1,579 +0,0 @@ -# coding=utf-8 -r""" -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 ChallengeList(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, identity): - """ - Initialize the ChallengeList - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeList - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeList - """ - super(ChallengeList, self).__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, expiration_date=values.unset, details=values.unset, - hidden_details=values.unset, twilio_sandbox_mode=values.unset): - """ - Create the ChallengeInstance - - :param unicode factor_sid: Factor Sid. - :param datetime expiration_date: The future date in which this Challenge will expire - :param unicode details: Public details provided to contextualize the Challenge - :param unicode hidden_details: Hidden details provided to contextualize the Challenge - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - - :returns: The created ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - data = values.of({ - 'FactorSid': factor_sid, - 'ExpirationDate': serialize.iso8601_datetime(expiration_date), - 'Details': details, - 'HiddenDetails': hidden_details, - }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - 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'], - ) - - def stream(self, factor_sid=values.unset, status=values.unset, - twilio_sandbox_mode=values.unset, limit=None, page_size=None): - """ - 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 unicode factor_sid: Factor Sid. - :param ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.challenge.ChallengeInstance] - """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - factor_sid=factor_sid, - status=status, - twilio_sandbox_mode=twilio_sandbox_mode, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['limit']) - - def list(self, factor_sid=values.unset, status=values.unset, - twilio_sandbox_mode=values.unset, limit=None, page_size=None): - """ - 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 unicode factor_sid: Factor Sid. - :param ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.challenge.ChallengeInstance] - """ - return list(self.stream( - factor_sid=factor_sid, - status=status, - twilio_sandbox_mode=twilio_sandbox_mode, - limit=limit, - page_size=page_size, - )) - - def page(self, factor_sid=values.unset, status=values.unset, - twilio_sandbox_mode=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): - """ - Retrieve a single page of ChallengeInstance records from the API. - Request is executed immediately - - :param unicode factor_sid: Factor Sid. - :param ChallengeInstance.ChallengeStatuses status: The Status of theChallenges to fetch - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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 ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengePage - """ - data = values.of({ - 'FactorSid': factor_sid, - 'Status': status, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) - - return ChallengePage(self._version, response, self._solution) - - def get_page(self, target_url): - """ - Retrieve a specific page of ChallengeInstance records from the API. - Request is executed immediately - - :param str target_url: API-generated URL for the requested results page - - :returns: Page of ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengePage - """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return ChallengePage(self._version, response, self._solution) - - def get(self, sid): - """ - Constructs a ChallengeContext - - :param sid: A string that uniquely identifies this Challenge. - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - """ - return ChallengeContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a ChallengeContext - - :param sid: A string that uniquely identifies this Challenge. - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - """ - return ChallengeContext( - 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 ChallengePage(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 ChallengePage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengePage - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengePage - """ - super(ChallengePage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of ChallengeInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - return ChallengeInstance( - 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 ChallengeContext(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, identity, sid): - """ - Initialize the ChallengeContext - - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity - :param sid: A string that uniquely identifies this Challenge. - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - """ - super(ChallengeContext, self).__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) - - def fetch(self, twilio_sandbox_mode=values.unset): - """ - Fetch the ChallengeInstance - - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - - :returns: The fetched ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - 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'], - ) - - def update(self, auth_payload=values.unset, twilio_sandbox_mode=values.unset): - """ - Update the ChallengeInstance - - :param unicode auth_payload: Optional payload to verify the Challenge - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - - :returns: The updated ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - data = values.of({'AuthPayload': auth_payload, }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - 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'], - ) - - 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 ChallengeInstance(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 ChallengeStatuses(object): - PENDING = "pending" - EXPIRED = "expired" - APPROVED = "approved" - DENIED = "denied" - - class ChallengeReasons(object): - NONE = "none" - NOT_NEEDED = "not_needed" - NOT_REQUESTED = "not_requested" - - class FactorTypes(object): - PUSH = "push" - - def __init__(self, version, payload, service_sid, identity, sid=None): - """ - Initialize the ChallengeInstance - - :returns: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - super(ChallengeInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'entity_sid': payload.get('entity_sid'), - 'identity': payload.get('identity'), - 'factor_sid': payload.get('factor_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'date_responded': deserialize.iso8601_datetime(payload.get('date_responded')), - 'expiration_date': deserialize.iso8601_datetime(payload.get('expiration_date')), - 'status': payload.get('status'), - 'responded_reason': payload.get('responded_reason'), - 'details': payload.get('details'), - 'hidden_details': payload.get('hidden_details'), - 'factor_type': payload.get('factor_type'), - 'url': payload.get('url'), - } - - # 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: ChallengeContext for this ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeContext - """ - 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 - - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Challenge. - :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 entity_sid(self): - """ - :returns: Entity Sid. - :rtype: unicode - """ - return self._properties['entity_sid'] - - @property - def identity(self): - """ - :returns: Unique external identifier of the Entity - :rtype: unicode - """ - return self._properties['identity'] - - @property - def factor_sid(self): - """ - :returns: Factor Sid. - :rtype: unicode - """ - return self._properties['factor_sid'] - - @property - def date_created(self): - """ - :returns: The date this Challenge was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The date this Challenge was updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def date_responded(self): - """ - :returns: The date this Challenge was responded - :rtype: datetime - """ - return self._properties['date_responded'] - - @property - def expiration_date(self): - """ - :returns: The date this Challenge is expired - :rtype: datetime - """ - return self._properties['expiration_date'] - - @property - def status(self): - """ - :returns: The Status of this Challenge - :rtype: ChallengeInstance.ChallengeStatuses - """ - return self._properties['status'] - - @property - def responded_reason(self): - """ - :returns: The Reason of this Challenge `status` - :rtype: ChallengeInstance.ChallengeReasons - """ - return self._properties['responded_reason'] - - @property - def details(self): - """ - :returns: Public details provided to contextualize the Challenge - :rtype: unicode - """ - return self._properties['details'] - - @property - def hidden_details(self): - """ - :returns: Hidden details provided to contextualize the Challenge - :rtype: unicode - """ - return self._properties['hidden_details'] - - @property - def factor_type(self): - """ - :returns: The Factor Type of this Challenge - :rtype: ChallengeInstance.FactorTypes - """ - return self._properties['factor_type'] - - @property - def url(self): - """ - :returns: The URL of this resource. - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self, twilio_sandbox_mode=values.unset): - """ - Fetch the ChallengeInstance - - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - - :returns: The fetched ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - return self._proxy.fetch(twilio_sandbox_mode=twilio_sandbox_mode, ) - - def update(self, auth_payload=values.unset, twilio_sandbox_mode=values.unset): - """ - Update the ChallengeInstance - - :param unicode auth_payload: Optional payload to verify the Challenge - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - - :returns: The updated ChallengeInstance - :rtype: twilio.rest.verify.v2.service.entity.challenge.ChallengeInstance - """ - return self._proxy.update(auth_payload=auth_payload, twilio_sandbox_mode=twilio_sandbox_mode, ) - - 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/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 index 4b5300d279..7bf91cd870 100644 --- a/twilio/rest/verify/v2/service/entity/factor.py +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -1,545 +1,728 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 FactorList(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, identity): - """ - Initialize the FactorList +class FactorInstance(InstanceResource): - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" - :returns: twilio.rest.verify.v2.service.entity.factor.FactorList - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorList - """ - super(FactorList, self).__init__(version) + 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") - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, } - self._uri = '/Services/{service_sid}/Entities/{identity}/Factors'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + self._context: Optional[FactorContext] = None - def create(self, binding, friendly_name, factor_type, config, - twilio_sandbox_mode=values.unset, authorization=values.unset): + @property + def _proxy(self) -> "FactorContext": """ - Create the FactorInstance - - :param unicode binding: A unique binding for this Factor as a json string - :param unicode friendly_name: The friendly name of this Factor - :param FactorInstance.FactorTypes factor_type: The Type of this Factor - :param unicode config: The config for this Factor as a json string - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :param unicode authorization: The Authorization HTTP request header + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance + :returns: FactorContext for this FactorInstance """ - data = values.of({ - 'Binding': binding, - 'FriendlyName': friendly_name, - 'FactorType': factor_type, - 'Config': config, - }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, 'Authorization': authorization, }) + 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 - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers, ) + def delete(self) -> bool: + """ + Deletes the FactorInstance - return FactorInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - ) - def stream(self, twilio_sandbox_mode=values.unset, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + return self._proxy.delete() - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.factor.FactorInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the FactorInstance - page = self.page(twilio_sandbox_mode=twilio_sandbox_mode, page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() - def list(self, twilio_sandbox_mode=values.unset, limit=None, page_size=None): + def fetch(self) -> "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. + Fetch the FactorInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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.verify.v2.service.entity.factor.FactorInstance] + :returns: The fetched FactorInstance """ - return list(self.stream(twilio_sandbox_mode=twilio_sandbox_mode, limit=limit, page_size=page_size, )) + return self._proxy.fetch() - def page(self, twilio_sandbox_mode=values.unset, page_token=values.unset, - page_number=values.unset, page_size=values.unset): + async def fetch_async(self) -> "FactorInstance": """ - Retrieve a single page of FactorInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the FactorInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header - :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 FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorPage + :returns: The fetched FactorInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers, ) + 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 - return FactorPage(self._version, response, self._solution) + :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`. - def get_page(self, target_url): + :returns: The updated FactorInstance """ - Retrieve a specific page of FactorInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorPage + :returns: The updated FactorInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return FactorPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a FactorContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A string that uniquely identifies this Factor. - :returns: twilio.rest.verify.v2.service.entity.factor.FactorContext - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorContext - """ - return FactorContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, - ) +class FactorContext(InstanceContext): - def __call__(self, sid): + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): """ - Constructs a FactorContext - - :param sid: A string that uniquely identifies this Factor. + Initialize the FactorContext - :returns: twilio.rest.verify.v2.service.entity.factor.FactorContext - :rtype: twilio.rest.verify.v2.service.entity.factor.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. """ - return FactorContext( - self._version, - service_sid=self._solution['service_sid'], - identity=self._solution['identity'], - sid=sid, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the FactorInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class FactorPage(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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the FactorPage + Asynchronous coroutine that deletes the FactorInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :param identity: Unique external identifier of the Entity - :returns: twilio.rest.verify.v2.service.entity.factor.FactorPage - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorPage + :returns: True if delete succeeds, False otherwise """ - super(FactorPage, 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) -> FactorInstance: """ - Build an instance of FactorInstance + Fetch the FactorInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.entity.factor.FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.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'], + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - def __repr__(self): + async def fetch_async(self) -> FactorInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the FactorInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched FactorInstance """ - return '' + headers = values.of({}) -class FactorContext(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, service_sid, identity, sid): - """ - Initialize the FactorContext + 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 identity: Unique external identifier of the Entity - :param sid: A string that uniquely identifies this Factor. + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) - :returns: twilio.rest.verify.v2.service.entity.factor.FactorContext - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorContext + 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: """ - super(FactorContext, self).__init__(version) + Update the FactorInstance - # Path Solution - self._solution = {'service_sid': service_sid, 'identity': identity, 'sid': sid, } - self._uri = '/Services/{service_sid}/Entities/{identity}/Factors/{sid}'.format(**self._solution) + :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`. - def delete(self, twilio_sandbox_mode=values.unset): + :returns: The updated FactorInstance """ - Deletes the FactorInstance - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + 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({}) - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return self._version.delete(method='DELETE', uri=self._uri, headers=headers, ) + headers["Accept"] = "application/json" - def fetch(self, twilio_sandbox_mode=values.unset): - """ - Fetch the FactorInstance + 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"], + ) - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + 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 fetched FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance + :returns: The updated FactorInstance """ - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) - payload = self._version.fetch(method='GET', uri=self._uri, headers=headers, ) + 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'], + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - def update(self, auth_payload=values.unset, friendly_name=values.unset, - config=values.unset, twilio_sandbox_mode=values.unset): + def __repr__(self) -> str: """ - Update the FactorInstance - - :param unicode auth_payload: Optional payload to verify the Factor for the first time - :param unicode friendly_name: The friendly name of this Factor - :param unicode config: The config for this Factor as a json string - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + Provide a friendly representation - :returns: The updated FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance + :returns: Machine friendly representation """ - data = values.of({'AuthPayload': auth_payload, 'FriendlyName': friendly_name, 'Config': config, }) - headers = values.of({'Twilio-Sandbox-Mode': twilio_sandbox_mode, }) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FactorPage(Page): - payload = self._version.update(method='POST', uri=self._uri, data=data, headers=headers, ) + 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'], - sid=self._solution['sid'], + service_sid=self._solution["service_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) + return "" -class FactorInstance(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 FactorList(ListResource): - class FactorStatuses(object): - UNVERIFIED = "unverified" - VERIFIED = "verified" + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the FactorList - class FactorTypes(object): - PUSH = "push" + :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. - def __init__(self, version, payload, service_sid, identity, sid=None): - """ - Initialize the FactorInstance - - :returns: twilio.rest.verify.v2.service.entity.factor.FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance - """ - super(FactorInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'entity_sid': payload.get('entity_sid'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'friendly_name': payload.get('friendly_name'), - 'status': payload.get('status'), - 'factor_type': payload.get('factor_type'), - 'config': payload.get('config'), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'identity': identity, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "identity": identity, } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) - @property - def _proxy(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FactorInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + 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. - :returns: FactorContext for this FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorContext - """ - 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 + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 Factor. - :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: 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[FactorInstance]: """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] + 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. - @property - def entity_sid(self): - """ - :returns: Entity Sid. - :rtype: unicode - """ - return self._properties['entity_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 identity(self): - """ - :returns: Unique external identifier of the Entity - :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(page_size=limits["page_size"]) - @property - def date_created(self): - """ - :returns: The date this Factor was created - :rtype: datetime - """ - return self._properties['date_created'] + return self._version.stream_async(page, limits["limit"]) - @property - def date_updated(self): - """ - :returns: The date this Factor was updated - :rtype: datetime + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: """ - return self._properties['date_updated'] + Lists FactorInstance 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 status(self): + :returns: list that will contain up to limit results """ - :returns: The Status of this Factor - :rtype: FactorInstance.FactorStatuses - """ - return self._properties['status'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def factor_type(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: """ - :returns: The Type of this Factor - :rtype: FactorInstance.FactorTypes + 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 self._properties['factor_type'] + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] - @property - def config(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, + ) -> FactorPage: """ - :returns: The config - :rtype: dict + 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 """ - return self._properties['config'] + 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 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: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - return self._properties['url'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def delete(self, twilio_sandbox_mode=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 FactorPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FactorPage: """ - Deletes the FactorInstance + Retrieve a specific page of FactorInstance records from the API. + Request is executed immediately - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Page of FactorInstance """ - return self._proxy.delete(twilio_sandbox_mode=twilio_sandbox_mode, ) + response = self._version.domain.twilio.request("GET", target_url) + return FactorPage(self._version, response, self._solution) - def fetch(self, twilio_sandbox_mode=values.unset): + async def get_page_async(self, target_url: str) -> FactorPage: """ - Fetch the FactorInstance + Asynchronously retrieve a specific page of FactorInstance records from the API. + Request is executed immediately - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + :param target_url: API-generated URL for the requested results page - :returns: The fetched FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance + :returns: Page of FactorInstance """ - return self._proxy.fetch(twilio_sandbox_mode=twilio_sandbox_mode, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return FactorPage(self._version, response, self._solution) - def update(self, auth_payload=values.unset, friendly_name=values.unset, - config=values.unset, twilio_sandbox_mode=values.unset): + def get(self, sid: str) -> FactorContext: """ - Update the FactorInstance + Constructs a FactorContext - :param unicode auth_payload: Optional payload to verify the Factor for the first time - :param unicode friendly_name: The friendly name of this Factor - :param unicode config: The config for this Factor as a json string - :param unicode twilio_sandbox_mode: The Twilio-Sandbox-Mode HTTP request header + :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, + ) - :returns: The updated FactorInstance - :rtype: twilio.rest.verify.v2.service.entity.factor.FactorInstance + def __call__(self, sid: str) -> FactorContext: """ - return self._proxy.update( - auth_payload=auth_payload, - friendly_name=friendly_name, - config=config, - twilio_sandbox_mode=twilio_sandbox_mode, + 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): + 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/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 index 2de0611af9..03f494f6e9 100644 --- a/twilio/rest/verify/v2/service/messaging_configuration.py +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -1,430 +1,640 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 MessagingConfigurationList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the MessagingConfigurationList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + self._solution = { + "service_sid": service_sid, + "country": country or self.country, + } + self._context: Optional[MessagingConfigurationContext] = None - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationList + @property + def _proxy(self) -> "MessagingConfigurationContext": """ - super(MessagingConfigurationList, 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}/MessagingConfigurations'.format(**self._solution) + :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 create(self, country, messaging_service_sid): + def delete(self) -> bool: """ - Create the MessagingConfigurationInstance + Deletes the MessagingConfigurationInstance - :param unicode country: The ISO-3166-1 country code of the country or `all`. - :param unicode messaging_service_sid: The SID of the Messaging Service used for this configuration. - :returns: The created MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Country': country, 'MessagingServiceSid': messaging_service_sid, }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance - return MessagingConfigurationInstance( - 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 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. + 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.verify.v2.service.messaging_configuration.MessagingConfigurationInstance] + def fetch(self) -> "MessagingConfigurationInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the MessagingConfigurationInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched MessagingConfigurationInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the MessagingConfigurationInstance - :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.verify.v2.service.messaging_configuration.MessagingConfigurationInstance] + :returns: The fetched MessagingConfigurationInstance """ - 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, messaging_service_sid: str) -> "MessagingConfigurationInstance": """ - Retrieve a single page of MessagingConfigurationInstance records from the API. - Request is executed immediately + Update the MessagingConfigurationInstance - :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 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: Page of MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :returns: The updated MessagingConfigurationInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return MessagingConfigurationPage(self._version, response, self._solution) + return self._proxy.update( + messaging_service_sid=messaging_service_sid, + ) - def get_page(self, target_url): + async def update_async( + self, messaging_service_sid: str + ) -> "MessagingConfigurationInstance": """ - Retrieve a specific page of MessagingConfigurationInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the MessagingConfigurationInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :returns: The updated MessagingConfigurationInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + messaging_service_sid=messaging_service_sid, ) - return MessagingConfigurationPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, country): + :returns: Machine friendly representation """ - Constructs a MessagingConfigurationContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param country: The ISO-3166-1 country code of the country or `all`. - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - """ - return MessagingConfigurationContext( - self._version, - service_sid=self._solution['service_sid'], - country=country, - ) +class MessagingConfigurationContext(InstanceContext): - def __call__(self, country): + def __init__(self, version: Version, service_sid: str, country: str): """ - Constructs a MessagingConfigurationContext - - :param country: The ISO-3166-1 country code of the country or `all`. + Initialize the MessagingConfigurationContext - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.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`. """ - return MessagingConfigurationContext( - self._version, - service_sid=self._solution['service_sid'], - country=country, + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "country": country, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations/{country}".format( + **self._solution ) - def __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the MessagingConfigurationInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class MessagingConfigurationPage(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 MessagingConfigurationPage + Asynchronous coroutine that deletes the MessagingConfigurationInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationPage + :returns: True if delete succeeds, False otherwise """ - super(MessagingConfigurationPage, 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) -> MessagingConfigurationInstance: """ - Build an instance of MessagingConfigurationInstance + Fetch the MessagingConfigurationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.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'], + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) - def __repr__(self): + async def fetch_async(self) -> MessagingConfigurationInstance: """ - Provide a friendly representation + Asynchronous coroutine to fetch the MessagingConfigurationInstance - :returns: Machine friendly representation - :rtype: str - """ - return '' - -class MessagingConfigurationContext(InstanceContext): - """ """ - - def __init__(self, version, service_sid, country): + :returns: The fetched MessagingConfigurationInstance """ - Initialize the MessagingConfigurationContext - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param country: The ISO-3166-1 country code of the country or `all`. + headers = values.of({}) - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext - """ - super(MessagingConfigurationContext, self).__init__(version) + headers["Accept"] = "application/json" - # Path Solution - self._solution = {'service_sid': service_sid, 'country': country, } - self._uri = '/Services/{service_sid}/MessagingConfigurations/{country}'.format(**self._solution) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def update(self, messaging_service_sid): + 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 unicode messaging_service_sid: The SID of the Messaging Service used for this configuration. + :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 - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance """ - data = values.of({'MessagingServiceSid': messaging_service_sid, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) - def fetch(self): + async def update_async( + self, messaging_service_sid: str + ) -> MessagingConfigurationInstance: """ - Fetch the MessagingConfigurationInstance + Asynchronous coroutine to update the MessagingConfigurationInstance - :returns: The fetched MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the MessagingConfigurationInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - def __repr__(self): + +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class MessagingConfigurationInstance(InstanceResource): - """ """ +class MessagingConfigurationList(ListResource): - def __init__(self, version, payload, service_sid, country=None): + def __init__(self, version: Version, service_sid: str): """ - Initialize the MessagingConfigurationInstance + 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. - :returns: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance """ - super(MessagingConfigurationInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'service_sid': payload.get('service_sid'), - 'country': payload.get('country'), - 'messaging_service_sid': payload.get('messaging_service_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), + # Path Solution + self._solution = { + "service_sid": service_sid, } + self._uri = "/Services/{service_sid}/MessagingConfigurations".format( + **self._solution + ) - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'country': country or self._properties['country'], } + def create( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Create the MessagingConfigurationInstance - @property - def _proxy(self): + :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 """ - 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 - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationContext + 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: """ - if self._context is None: - self._context = MessagingConfigurationContext( - self._version, - service_sid=self._solution['service_sid'], - country=self._solution['country'], - ) - return self._context + Asynchronously create the MessagingConfigurationInstance - @property - def account_sid(self): + :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 """ - :returns: The SID of the Account that created the resource - :rtype: unicode + + 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]: """ - return self._properties['account_sid'] + 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. - @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 """ - :returns: The SID of the Service that the resource is associated with - :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[MessagingConfigurationInstance]: """ - return self._properties['service_sid'] + 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. - @property - def country(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 ISO-3166-1 country code of the country or `all`. - :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[MessagingConfigurationInstance]: """ - return self._properties['country'] + Lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - @property - def messaging_service_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 SID of the Messaging Service used for this configuration. - :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[MessagingConfigurationInstance]: """ - return self._properties['messaging_service_sid'] + 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. - @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 RFC 2822 date and time in GMT when the resource was 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, + ) -> MessagingConfigurationPage: """ - return self._properties['date_created'] + Retrieve a single page of MessagingConfigurationInstance 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 MessagingConfigurationInstance """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of MessagingConfigurationInstance 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 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: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) - def update(self, messaging_service_sid): + async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: """ - Update the MessagingConfigurationInstance + Asynchronously retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately - :param unicode messaging_service_sid: The SID of the Messaging Service used for this configuration. + :param target_url: API-generated URL for the requested results page - :returns: The updated MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.MessagingConfigurationInstance + :returns: Page of MessagingConfigurationInstance """ - return self._proxy.update(messaging_service_sid, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) - def fetch(self): + def get(self, country: str) -> MessagingConfigurationContext: """ - Fetch the MessagingConfigurationInstance + Constructs a MessagingConfigurationContext - :returns: The fetched MessagingConfigurationInstance - :rtype: twilio.rest.verify.v2.service.messaging_configuration.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`. """ - return self._proxy.fetch() + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=country + ) - def delete(self): + def __call__(self, country: str) -> MessagingConfigurationContext: """ - Deletes the MessagingConfigurationInstance + Constructs a MessagingConfigurationContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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 self._proxy.delete() + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=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/verify/v2/service/rate_limit/__init__.py b/twilio/rest/verify/v2/service/rate_limit/__init__.py index 0175cdfc6b..ced5ab6a64 100644 --- a/twilio/rest/verify/v2/service/rate_limit/__init__.py +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -1,462 +1,667 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.verify.v2.service.rate_limit.bucket import BucketList -class RateLimitList(ListResource): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the RateLimitList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RateLimitContext] = None - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitList - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitList + @property + def _proxy(self) -> "RateLimitContext": """ - super(RateLimitList, self).__init__(version) - - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/RateLimits'.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, description=values.unset): + :returns: RateLimitContext for this RateLimitInstance """ - Create the RateLimitInstance - - :param unicode unique_name: A unique, developer assigned name of this Rate Limit. - :param unicode description: Description of this Rate Limit + if self._context is None: + self._context = RateLimitContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - :returns: The created RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + def delete(self) -> bool: """ - data = values.of({'UniqueName': unique_name, 'Description': description, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Deletes the RateLimitInstance - return RateLimitInstance(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 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 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.verify.v2.service.rate_limit.RateLimitInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the RateLimitInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch the RateLimitInstance - :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.verify.v2.service.rate_limit.RateLimitInstance] + :returns: The fetched RateLimitInstance """ - 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) -> "RateLimitInstance": """ - Retrieve a single page of RateLimitInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the RateLimitInstance - :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 RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitPage + :returns: The fetched RateLimitInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RateLimitPage(self._version, response, self._solution) + return await self._proxy.fetch_async() - def get_page(self, target_url): + def update( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": """ - Retrieve a specific page of RateLimitInstance records from the API. - Request is executed immediately + Update the RateLimitInstance - :param str target_url: API-generated URL for the requested results page + :param description: Description of this Rate Limit - :returns: Page of RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitPage + :returns: The updated RateLimitInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + description=description, ) - return RateLimitPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": """ - Constructs a RateLimitContext + Asynchronous coroutine to update the RateLimitInstance - :param sid: The unique string that identifies the resource + :param description: Description of this Rate Limit - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitContext - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + :returns: The updated RateLimitInstance """ - return RateLimitContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + description=description, + ) - def __call__(self, sid): + @property + def buckets(self) -> BucketList: """ - Constructs a RateLimitContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitContext - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + Access the buckets """ - return RateLimitContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.buckets - 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 RateLimitPage(Page): - """ """ +class RateLimitContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the RateLimitPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the RateLimitContext - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitPage - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitPage + :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(RateLimitPage, 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}/RateLimits/{sid}".format(**self._solution) + + self._buckets: Optional[BucketList] = None - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of RateLimitInstance + Deletes the RateLimitInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :returns: True if delete succeeds, False otherwise """ - return RateLimitInstance(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 RateLimitInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class RateLimitContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, service_sid, sid): + def fetch(self) -> RateLimitInstance: """ - Initialize the RateLimitContext + Fetch the RateLimitInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param sid: The unique string that identifies the resource - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitContext - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + :returns: The fetched RateLimitInstance """ - super(RateLimitContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/RateLimits/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - # Dependents - self._buckets = None + 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"], + ) - def update(self, description=values.unset): + async def fetch_async(self) -> RateLimitInstance: """ - Update the RateLimitInstance + Asynchronous coroutine to fetch the RateLimitInstance - :param unicode description: Description of this Rate Limit - :returns: The updated RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :returns: The fetched RateLimitInstance """ - data = values.of({'Description': description, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def fetch(self): + def update( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: """ - Fetch the RateLimitInstance + Update the RateLimitInstance - :returns: The fetched RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + async def update_async( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: """ - Deletes the RateLimitInstance + Asynchronous coroutine to update the RateLimitInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance """ - return self._version.delete(method='DELETE', uri=self._uri, ) + + 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): + def buckets(self) -> BucketList: """ Access the buckets - - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList """ if self._buckets is None: self._buckets = BucketList( self._version, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['sid'], + self._solution["service_sid"], + self._solution["sid"], ) return self._buckets - 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 RateLimitInstance(InstanceResource): - """ """ +class RateLimitPage(Page): - def __init__(self, version, payload, service_sid, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: """ - Initialize the RateLimitInstance + Build an instance of RateLimitInstance - :returns: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :param payload: Payload response from the API """ - super(RateLimitInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'unique_name': payload.get('unique_name'), - 'description': payload.get('description'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_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: RateLimitContext for this RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = RateLimitContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + return "" - @property - def sid(self): + +class RateLimitList(ListResource): + + def __init__(self, version: Version, service_sid: str): """ - :returns: A string that uniquely identifies this Rate Limit. - :rtype: unicode + 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. + """ - return self._properties['sid'] + super().__init__(version) - @property - def service_sid(self): + # 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: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + 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 """ - return self._properties['service_sid'] - @property - def account_sid(self): + 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: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def unique_name(self): + 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]: """ - :returns: A unique, developer assigned name of this Rate Limit. - :rtype: unicode + 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 """ - return self._properties['unique_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def description(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RateLimitInstance]: """ - :returns: Description of this Rate Limit - :rtype: unicode + 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 """ - return self._properties['description'] + 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[RateLimitInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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 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[RateLimitInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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 self._properties['date_updated'] + 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, + ) -> RateLimitPage: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - 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 = 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: """ - :returns: The URLs of related resources - :rtype: unicode + 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 """ - 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, self._solution) - def update(self, description=values.unset): + def get_page(self, target_url: str) -> RateLimitPage: """ - Update the RateLimitInstance + Retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately - :param unicode description: Description of this Rate Limit + :param target_url: API-generated URL for the requested results page - :returns: The updated RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :returns: Page of RateLimitInstance """ - return self._proxy.update(description=description, ) + response = self._version.domain.twilio.request("GET", target_url) + return RateLimitPage(self._version, response, self._solution) - def fetch(self): + async def get_page_async(self, target_url: str) -> RateLimitPage: """ - Fetch the RateLimitInstance + Asynchronously retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately - :returns: The fetched RateLimitInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.RateLimitInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance """ - return self._proxy.fetch() + response = await self._version.domain.twilio.request_async("GET", target_url) + return RateLimitPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> RateLimitContext: """ - Deletes the RateLimitInstance + Constructs a RateLimitContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. """ - return self._proxy.delete() + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - @property - def buckets(self): + def __call__(self, sid: str) -> RateLimitContext: """ - Access the buckets + Constructs a RateLimitContext - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. """ - return self._proxy.buckets + return RateLimitContext( + 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/verify/v2/service/rate_limit/bucket.py b/twilio/rest/verify/v2/service/rate_limit/bucket.py index ff86f777b2..4ac50cfc2f 100644 --- a/twilio/rest/verify/v2/service/rate_limit/bucket.py +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -1,464 +1,692 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 BucketList(ListResource): - """ """ - - def __init__(self, version, service_sid, rate_limit_sid): - """ - Initialize the BucketList +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") - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param rate_limit_sid: Rate Limit Sid. + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid or self.sid, + } + self._context: Optional[BucketContext] = None - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketList + @property + def _proxy(self) -> "BucketContext": """ - super(BucketList, 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, 'rate_limit_sid': rate_limit_sid, } - self._uri = '/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets'.format(**self._solution) + :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 create(self, max, interval): + def delete(self) -> bool: """ - Create the BucketInstance + Deletes the BucketInstance - :param unicode max: Max number of requests. - :param unicode interval: Number of seconds that the rate limit will be enforced over. - :returns: The created BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'Max': max, 'Interval': interval, }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance - return BucketInstance( - self._version, - payload, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['rate_limit_sid'], - ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 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.verify.v2.service.rate_limit.bucket.BucketInstance] + def fetch(self) -> "BucketInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the BucketInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the BucketInstance - :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.verify.v2.service.rate_limit.bucket.BucketInstance] + :returns: The fetched BucketInstance """ - 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, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": """ - Retrieve a single page of BucketInstance records from the API. - Request is executed immediately + Update the BucketInstance - :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 max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. - :returns: Page of BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + :returns: The updated BucketInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return BucketPage(self._version, response, self._solution) + return self._proxy.update( + max=max, + interval=interval, + ) - def get_page(self, target_url): + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": """ - Retrieve a specific page of BucketInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the BucketInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + :returns: The updated BucketInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + max=max, + interval=interval, ) - return BucketPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a BucketContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: A string that uniquely identifies this Bucket. - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - """ - return BucketContext( - self._version, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['rate_limit_sid'], - sid=sid, - ) +class BucketContext(InstanceContext): - def __call__(self, sid): + def __init__( + self, version: Version, service_sid: str, rate_limit_sid: str, sid: str + ): """ - Constructs a BucketContext - - :param sid: A string that uniquely identifies this Bucket. + Initialize the BucketContext - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.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. """ - return BucketContext( - self._version, - service_sid=self._solution['service_sid'], - rate_limit_sid=self._solution['rate_limit_sid'], - sid=sid, + 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 __repr__(self): + def delete(self) -> bool: """ - Provide a friendly representation + Deletes the BucketInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class BucketPage(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 BucketPage + Asynchronous coroutine that deletes the BucketInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with - :param rate_limit_sid: Rate Limit Sid. - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketPage + :returns: True if delete succeeds, False otherwise """ - super(BucketPage, 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) -> BucketInstance: """ - Build an instance of BucketInstance + Fetch the BucketInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.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'], + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> BucketInstance: """ - return '' - + Asynchronous coroutine to fetch the BucketInstance -class BucketContext(InstanceContext): - """ """ - def __init__(self, version, service_sid, rate_limit_sid, sid): + :returns: The fetched BucketInstance """ - Initialize the BucketContext - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with - :param rate_limit_sid: Rate Limit Sid. - :param sid: A string that uniquely identifies this Bucket. + headers = values.of({}) - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - """ - super(BucketContext, self).__init__(version) + headers["Accept"] = "application/json" - # 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) + 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=values.unset, interval=values.unset): + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: """ Update the BucketInstance - :param unicode max: Max number of requests. - :param unicode interval: Number of seconds that the rate limit will be enforced over. + :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 - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance """ - data = values.of({'Max': max, 'Interval': interval, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - def fetch(self): + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: """ - Fetch the BucketInstance + Asynchronous coroutine to update the BucketInstance - :returns: The fetched BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - def delete(self): + def __repr__(self) -> str: """ - Deletes the BucketInstance + Provide a friendly representation - :returns: True if delete succeeds, False otherwise - :rtype: bool + :returns: Machine friendly representation """ - return self._version.delete(method='DELETE', uri=self._uri, ) + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - def __repr__(self): +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 - :rtype: str """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + return "" -class BucketInstance(InstanceResource): - """ """ +class BucketList(ListResource): - def __init__(self, version, payload, service_sid, rate_limit_sid, sid=None): + def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): """ - Initialize the BucketInstance + Initialize the BucketList - :returns: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance - """ - super(BucketInstance, self).__init__(version) + :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. - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'rate_limit_sid': payload.get('rate_limit_sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'max': deserialize.integer(payload.get('max')), - 'interval': deserialize.integer(payload.get('interval')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + """ + super().__init__(version) - # Context - self._context = None + # Path Solution self._solution = { - 'service_sid': service_sid, - 'rate_limit_sid': rate_limit_sid, - 'sid': sid or self._properties['sid'], + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets".format( + **self._solution + ) + ) - @property - def _proxy(self): + def create(self, max: int, interval: int) -> BucketInstance: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Create the BucketInstance - :returns: BucketContext for this BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketContext - """ - 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 + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. - @property - def sid(self): - """ - :returns: A string that uniquely identifies this Bucket. - :rtype: unicode + :returns: The created BucketInstance """ - return self._properties['sid'] - @property - def rate_limit_sid(self): + 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: """ - :returns: Rate Limit Sid. - :rtype: unicode + 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 """ - return self._properties['rate_limit_sid'] - @property - def service_sid(self): + 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]: """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + 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 """ - return self._properties['service_sid'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def account_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BucketInstance]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - 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 max(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: """ - :returns: Max number of requests. - :rtype: unicode + 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 self._properties['max'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def interval(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: """ - :returns: Number of seconds that the rate limit will be enforced over. - :rtype: unicode + 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 self._properties['interval'] + 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, + ) -> BucketPage: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The URL of this resource. - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return BucketPage(self._version, response, self._solution) - def update(self, max=values.unset, interval=values.unset): + async def get_page_async(self, target_url: str) -> BucketPage: """ - Update the BucketInstance + Asynchronously retrieve a specific page of BucketInstance records from the API. + Request is executed immediately - :param unicode max: Max number of requests. - :param unicode interval: Number of seconds that the rate limit will be enforced over. + :param target_url: API-generated URL for the requested results page - :returns: The updated BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + :returns: Page of BucketInstance """ - return self._proxy.update(max=max, interval=interval, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return BucketPage(self._version, response, self._solution) - def fetch(self): + def get(self, sid: str) -> BucketContext: """ - Fetch the BucketInstance + Constructs a BucketContext - :returns: The fetched BucketInstance - :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance + :param sid: A 34 character string that uniquely identifies this Bucket. """ - return self._proxy.fetch() + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=sid, + ) - def delete(self): + def __call__(self, sid: str) -> BucketContext: """ - Deletes the BucketInstance + Constructs a BucketContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: A 34 character string that uniquely identifies this Bucket. """ - return self._proxy.delete() + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_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/verify/v2/service/verification.py b/twilio/rest/verify/v2/service/verification.py index 0d8ee95774..64988a5983 100644 --- a/twilio/rest/verify/v2/service/verification.py +++ b/twilio/rest/verify/v2/service/verification.py @@ -1,417 +1,517 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 +from twilio.base.version import Version -class VerificationList(ListResource): - """ """ +class VerificationInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the VerificationList + class Channel(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + SNA = "sna" + + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + class Status(object): + CANCELED = "canceled" + APPROVED = "approved" - :returns: twilio.rest.verify.v2.service.verification.VerificationList - :rtype: twilio.rest.verify.v2.service.verification.VerificationList + """ + :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": """ - super(VerificationList, 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}/Verifications'.format(**self._solution) + :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 create(self, to, channel, custom_message=values.unset, - send_digits=values.unset, locale=values.unset, - custom_code=values.unset, amount=values.unset, payee=values.unset, - rate_limits=values.unset, channel_configuration=values.unset, - app_hash=values.unset): + def fetch(self) -> "VerificationInstance": """ - Create the VerificationInstance + Fetch the VerificationInstance - :param unicode to: The phone number or email to verify - :param unicode channel: The verification method to use - :param unicode custom_message: The text of a custom message to use for the verification - :param unicode send_digits: The digits to send after a phone call is answered - :param unicode locale: The locale to use for the verification SMS or call - :param unicode custom_code: A pre-generated code - :param unicode amount: The amount of the associated PSD2 compliant transaction. - :param unicode payee: The payee of the associated PSD2 compliant transaction - :param dict rate_limits: The custom key-value pairs of Programmable Rate Limits. - :param dict channel_configuration: Channel specific configuration in json format. - :param unicode app_hash: Your App Hash to be appended at the end of an SMS. - :returns: The created VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :returns: The fetched VerificationInstance """ - data = values.of({ - 'To': to, - 'Channel': channel, - '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, - }) + return self._proxy.fetch() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def fetch_async(self) -> "VerificationInstance": + """ + Asynchronous coroutine to fetch the VerificationInstance - return VerificationInstance(self._version, payload, service_sid=self._solution['service_sid'], ) - def get(self, sid): + :returns: The fetched VerificationInstance """ - Constructs a VerificationContext + return await self._proxy.fetch_async() - :param sid: The unique string that identifies the resource + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": + """ + Update the VerificationInstance + + :param status: - :returns: twilio.rest.verify.v2.service.verification.VerificationContext - :rtype: twilio.rest.verify.v2.service.verification.VerificationContext + :returns: The updated VerificationInstance """ - return VerificationContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return self._proxy.update( + status=status, + ) - def __call__(self, sid): + async def update_async( + self, status: "VerificationInstance.Status" + ) -> "VerificationInstance": """ - Constructs a VerificationContext + Asynchronous coroutine to update the VerificationInstance - :param sid: The unique string that identifies the resource + :param status: - :returns: twilio.rest.verify.v2.service.verification.VerificationContext - :rtype: twilio.rest.verify.v2.service.verification.VerificationContext + :returns: The updated VerificationInstance """ - return VerificationContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + return await self._proxy.update_async( + status=status, + ) - 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 VerificationPage(Page): - """ """ +class VerificationContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str, sid: str): """ - Initialize the VerificationPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + Initialize the VerificationContext - :returns: twilio.rest.verify.v2.service.verification.VerificationPage - :rtype: twilio.rest.verify.v2.service.verification.VerificationPage + :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(VerificationPage, 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}/Verifications/{sid}".format( + **self._solution + ) - def get_instance(self, payload): + def fetch(self) -> VerificationInstance: """ - Build an instance of VerificationInstance + Fetch the VerificationInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.verification.VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :returns: The fetched VerificationInstance """ - return VerificationInstance(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 VerificationContext(InstanceContext): - """ """ + return VerificationInstance( + 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) -> VerificationInstance: """ - Initialize the VerificationContext + Asynchronous coroutine to fetch the VerificationInstance - :param Version version: Version that contains the resource - :param service_sid: The SID of the verification Service to fetch the resource from - :param sid: The unique string that identifies the resource - :returns: twilio.rest.verify.v2.service.verification.VerificationContext - :rtype: twilio.rest.verify.v2.service.verification.VerificationContext + :returns: The fetched VerificationInstance """ - super(VerificationContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Verifications/{sid}'.format(**self._solution) + headers = values.of({}) + + headers["Accept"] = "application/json" - def update(self, status): + 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 VerificationInstance.Status status: The new status of the resource + :param status: :returns: The updated VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def fetch(self): + async def update_async( + self, status: "VerificationInstance.Status" + ) -> VerificationInstance: """ - Fetch the VerificationInstance + Asynchronous coroutine to update the VerificationInstance - :returns: The fetched VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :param status: + + :returns: The updated VerificationInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], + 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 VerificationInstance(InstanceResource): - """ """ - class Channel(object): - SMS = "sms" - CALL = "call" - EMAIL = "email" - - class Status(object): - CANCELED = "canceled" - APPROVED = "approved" +class VerificationList(ListResource): - def __init__(self, version, payload, service_sid, sid=None): - """ - Initialize the VerificationInstance - - :returns: twilio.rest.verify.v2.service.verification.VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance - """ - super(VerificationInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'to': payload.get('to'), - 'channel': payload.get('channel'), - 'status': payload.get('status'), - 'valid': payload.get('valid'), - 'lookup': payload.get('lookup'), - 'amount': payload.get('amount'), - 'payee': payload.get('payee'), - 'send_code_attempts': payload.get('send_code_attempts'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + def __init__(self, version: Version, service_sid: str): + """ + Initialize the VerificationList - # 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 verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. - @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: VerificationContext for this VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationContext + # 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: """ - if self._context is None: - self._context = VerificationContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + Create the VerificationInstance - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + :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. - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + :returns: The created VerificationInstance """ - return self._properties['service_sid'] - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + 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"}) - @property - def to(self): - """ - :returns: The phone number or email being verified - :rtype: unicode - """ - return self._properties['to'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def channel(self): - """ - :returns: The verification method used. - :rtype: VerificationInstance.Channel - """ - return self._properties['channel'] + headers["Accept"] = "application/json" - @property - def status(self): - """ - :returns: The status of the verification resource - :rtype: unicode - """ - return self._properties['status'] + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def valid(self): - """ - :returns: Whether the verification was successful - :rtype: bool - """ - return self._properties['valid'] + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - @property - def lookup(self): - """ - :returns: Information about the phone number being verified - :rtype: dict - """ - return self._properties['lookup'] + 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. - @property - def amount(self): - """ - :returns: The amount of the associated PSD2 compliant transaction. - :rtype: unicode + :returns: The created VerificationInstance """ - return self._properties['amount'] - @property - def payee(self): - """ - :returns: The payee of the associated PSD2 compliant transaction - :rtype: unicode - """ - return self._properties['payee'] + 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"}) - @property - def send_code_attempts(self): - """ - :returns: An array of verification attempt objects. - :rtype: dict - """ - return self._properties['send_code_attempts'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + headers["Accept"] = "application/json" - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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 url(self): - """ - :returns: The absolute URL of the Verification resource - :rtype: unicode - """ - return self._properties['url'] + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def update(self, status): + def get(self, sid: str) -> VerificationContext: """ - Update the VerificationInstance - - :param VerificationInstance.Status status: The new status of the resource + Constructs a VerificationContext - :returns: The updated VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. """ - return self._proxy.update(status, ) + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> VerificationContext: """ - Fetch the VerificationInstance + Constructs a VerificationContext - :returns: The fetched VerificationInstance - :rtype: twilio.rest.verify.v2.service.verification.VerificationInstance + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. """ - return self._proxy.fetch() + return VerificationContext( + 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/verify/v2/service/verification_check.py b/twilio/rest/verify/v2/service/verification_check.py index 9fcd55f466..c09057ebe1 100644 --- a/twilio/rest/verify/v2/service/verification_check.py +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -1,242 +1,202 @@ -# coding=utf-8 r""" -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): - """ """ - - def __init__(self, version, service_sid): - """ - Initialize the VerificationCheckList + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - :param Version version: Version that contains the resource - :param service_sid: The SID of the Service that the resource is associated with + Twilio - Verify + This is the public Twilio REST API. - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckList - """ - super(VerificationCheckList, self).__init__(version) + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/VerificationCheck'.format(**self._solution) +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values - def create(self, code, to=values.unset, verification_sid=values.unset, - amount=values.unset, payee=values.unset): - """ - Create the VerificationCheckInstance - - :param unicode code: The verification string - :param unicode to: The phone number or email to verify - :param unicode verification_sid: A SID that uniquely identifies the Verification Check - :param unicode amount: The amount of the associated PSD2 compliant transaction. - :param unicode payee: The payee of the associated PSD2 compliant transaction +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version - :returns: The created VerificationCheckInstance - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckInstance - """ - data = values.of({ - 'Code': code, - 'To': to, - 'VerificationSid': verification_sid, - 'Amount': amount, - 'Payee': payee, - }) - payload = self._version.create(method='POST', uri=self._uri, data=data, ) +class VerificationCheckInstance(InstanceResource): - return VerificationCheckInstance(self._version, payload, service_sid=self._solution['service_sid'], ) + 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): + 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 VerificationCheckPage(Page): - """ """ +class VerificationCheckList(ListResource): - def __init__(self, version, response, solution): + def __init__(self, version: Version, service_sid: str): """ - Initialize the VerificationCheckPage + Initialize the VerificationCheckList - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: The SID of the Service that the resource is associated with + :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. - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckPage - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckPage """ - super(VerificationCheckPage, self).__init__(version, response) + super().__init__(version) # 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.verify.v2.service.verification_check.VerificationCheckInstance - :rtype: twilio.rest.verify.v2.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): - """ """ - - class Channel(object): - SMS = "sms" - CALL = "call" - EMAIL = "email" - - def __init__(self, version, payload, service_sid): - """ - Initialize the VerificationCheckInstance - - :returns: twilio.rest.verify.v2.service.verification_check.VerificationCheckInstance - :rtype: twilio.rest.verify.v2.service.verification_check.VerificationCheckInstance - """ - super(VerificationCheckInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'to': payload.get('to'), - 'channel': payload.get('channel'), - 'status': payload.get('status'), - 'valid': payload.get('valid'), - 'amount': payload.get('amount'), - 'payee': payload.get('payee'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), + self._solution = { + "service_sid": service_sid, } - - # Context - self._context = None - self._solution = {'service_sid': service_sid, } - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def service_sid(self): - """ - :returns: The SID of the Service that the resource is associated with - :rtype: unicode + 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: """ - return self._properties['service_sid'] + Create the VerificationCheckInstance - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + :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. - @property - def to(self): - """ - :returns: The phone number or email being verified - :rtype: unicode + :returns: The created VerificationCheckInstance """ - return self._properties['to'] - @property - def channel(self): - """ - :returns: The verification method to use - :rtype: VerificationCheckInstance.Channel - """ - return self._properties['channel'] + 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. - @property - def status(self): - """ - :returns: The status of the verification resource - :rtype: unicode + :returns: The created VerificationCheckInstance """ - return self._properties['status'] - @property - def valid(self): - """ - :returns: Whether the verification was successful - :rtype: bool - """ - return self._properties['valid'] + 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"}) - @property - def amount(self): - """ - :returns: The amount of the associated PSD2 compliant transaction. - :rtype: unicode - """ - return self._properties['amount'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def payee(self): - """ - :returns: The payee of the associated PSD2 compliant transaction - :rtype: unicode - """ - return self._properties['payee'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the Verification Check resource was created - :rtype: datetime - """ - return self._properties['date_created'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the Verification Check resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + return VerificationCheckInstance( + 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/verify/v2/service/webhook.py b/twilio/rest/verify/v2/service/webhook.py index e2333d8538..dd68cf301b 100644 --- a/twilio/rest/verify/v2/service/webhook.py +++ b/twilio/rest/verify/v2/service/webhook.py @@ -1,492 +1,739 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 WebhookList(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 WebhookInstance(InstanceResource): - def __init__(self, version, service_sid): - """ - Initialize the WebhookList + class Methods(object): + GET = "GET" + POST = "POST" - :param Version version: Version that contains the resource - :param service_sid: Service Sid. + class Status(object): + ENABLED = "enabled" + DISABLED = "disabled" - :returns: twilio.rest.verify.v2.service.webhook.WebhookList - :rtype: twilio.rest.verify.v2.service.webhook.WebhookList - """ - super(WebhookList, self).__init__(version) + 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") - # Path Solution - self._solution = {'service_sid': service_sid, } - self._uri = '/Services/{service_sid}/Webhooks'.format(**self._solution) + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None - def create(self, friendly_name, event_types, webhook_url, status=values.unset): + @property + def _proxy(self) -> "WebhookContext": """ - Create the WebhookInstance - - :param unicode friendly_name: The string that you assigned to describe the webhook - :param unicode event_types: The array of events that this Webhook is subscribed to. - :param unicode webhook_url: The URL associated with this Webhook. - :param WebhookInstance.Status status: The webhook status + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :returns: The created WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance + :returns: WebhookContext for this WebhookInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EventTypes': serialize.map(event_types, lambda e: e), - 'WebhookUrl': webhook_url, - 'Status': status, - }) + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def delete(self) -> bool: + """ + Deletes the WebhookInstance - return WebhookInstance(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 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 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.verify.v2.service.webhook.WebhookInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the WebhookInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch the WebhookInstance - :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.verify.v2.service.webhook.WebhookInstance] + :returns: The fetched WebhookInstance """ - 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) -> "WebhookInstance": """ - Retrieve a single page of WebhookInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the WebhookInstance - :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 WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookPage + :returns: The fetched WebhookInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return await self._proxy.fetch_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return WebhookPage(self._version, response, self._solution) + :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: - def get_page(self, target_url): + :returns: The updated WebhookInstance """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately + 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 str target_url: API-generated URL for the requested results page + :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: Page of WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookPage + :returns: The updated WebhookInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + version=version, ) - return WebhookPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a WebhookContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + - :param sid: The unique string that identifies the resource to fetch +class WebhookContext(InstanceContext): - :returns: twilio.rest.verify.v2.service.webhook.WebhookContext - :rtype: twilio.rest.verify.v2.service.webhook.WebhookContext + def __init__(self, version: Version, service_sid: str, sid: str): """ - return WebhookContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Initialize the WebhookContext - def __call__(self, sid): + :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. """ - Constructs a WebhookContext + super().__init__(version) - :param sid: The unique string that identifies the resource to fetch + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) - :returns: twilio.rest.verify.v2.service.webhook.WebhookContext - :rtype: twilio.rest.verify.v2.service.webhook.WebhookContext + def delete(self) -> bool: """ - return WebhookContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) + Deletes the WebhookInstance - 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 WebhookPage(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 self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, response, solution): + async def delete_async(self) -> bool: """ - Initialize the WebhookPage + Asynchronous coroutine that deletes the WebhookInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param service_sid: Service Sid. - :returns: twilio.rest.verify.v2.service.webhook.WebhookPage - :rtype: twilio.rest.verify.v2.service.webhook.WebhookPage + :returns: True if delete succeeds, False otherwise """ - super(WebhookPage, 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) -> WebhookInstance: """ - Build an instance of WebhookInstance + Fetch the WebhookInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.verify.v2.service.webhook.WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance + :returns: The fetched WebhookInstance """ - return WebhookInstance(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 WebhookContext(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 WebhookInstance( + 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) -> WebhookInstance: """ - Initialize the WebhookContext + Asynchronous coroutine to fetch the WebhookInstance - :param Version version: Version that contains the resource - :param service_sid: Service Sid. - :param sid: The unique string that identifies the resource to fetch - :returns: twilio.rest.verify.v2.service.webhook.WebhookContext - :rtype: twilio.rest.verify.v2.service.webhook.WebhookContext + :returns: The fetched WebhookInstance """ - super(WebhookContext, self).__init__(version) - # Path Solution - self._solution = {'service_sid': service_sid, 'sid': sid, } - self._uri = '/Services/{service_sid}/Webhooks/{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 WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, event_types=values.unset, - webhook_url=values.unset, status=values.unset): + 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 unicode friendly_name: The string that you assigned to describe the webhook - :param unicode event_types: The array of events that this Webhook is subscribed to. - :param unicode webhook_url: The URL associated with this Webhook. - :param WebhookInstance.Status status: The webhook status + :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 - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'EventTypes': serialize.map(event_types, lambda e: e), - 'WebhookUrl': webhook_url, - 'Status': status, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - def delete(self): + 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: """ - Deletes the WebhookInstance + Asynchronous coroutine to update the WebhookInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + :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: - def fetch(self): + :returns: The updated WebhookInstance """ - Fetch the WebhookInstance - :returns: The fetched WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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'], + 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 WebhookInstance(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 WebhookPage(Page): - class Status(object): - ENABLED = "enabled" - DISABLED = "disabled" + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance - class Methods(object): - GET = "GET" - POST = "POST" + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) - def __init__(self, version, payload, service_sid, sid=None): + def __repr__(self) -> str: """ - Initialize the WebhookInstance + Provide a friendly representation - :returns: twilio.rest.verify.v2.service.webhook.WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance + :returns: Machine friendly representation """ - super(WebhookInstance, self).__init__(version) + return "" - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'service_sid': payload.get('service_sid'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'event_types': payload.get('event_types'), - 'status': payload.get('status'), - 'webhook_url': payload.get('webhook_url'), - 'webhook_method': payload.get('webhook_method'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } - # Context - self._context = None - self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } +class WebhookList(ListResource): - @property - def _proxy(self): + 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 WebhookList - :returns: WebhookContext for this WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookContext - """ - if self._context is None: - self._context = WebhookContext( - self._version, - service_sid=self._solution['service_sid'], - sid=self._solution['sid'], - ) - return self._context + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode """ - return self._properties['sid'] + super().__init__(version) - @property - def service_sid(self): - """ - :returns: Service Sid. - :rtype: unicode - """ - return self._properties['service_sid'] + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) - @property - def account_sid(self): + 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: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def friendly_name(self): + 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: """ - :returns: The string that you assigned to describe the webhook - :rtype: unicode + 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 """ - return self._properties['friendly_name'] - @property - def event_types(self): + 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]: """ - :returns: The array of events that this Webhook is subscribed to. - :rtype: unicode + 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 """ - return self._properties['event_types'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def status(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: """ - :returns: The webhook status - :rtype: WebhookInstance.Status + 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 """ - return self._properties['status'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def webhook_url(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - :returns: The URL associated with this Webhook. - :rtype: unicode + 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 self._properties['webhook_url'] + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - @property - def webhook_method(self): + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: """ - :returns: The method used when calling the webhook's URL. - :rtype: WebhookInstance.Methods + 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 self._properties['webhook_method'] + 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, + ) -> WebhookPage: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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 """ - 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 = 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: """ - :returns: The absolute URL of the Webhook resource - :rtype: unicode + 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 """ - return self._properties['url'] + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) - def update(self, friendly_name=values.unset, event_types=values.unset, - webhook_url=values.unset, status=values.unset): + async def get_page_async(self, target_url: str) -> WebhookPage: """ - Update the WebhookInstance + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately - :param unicode friendly_name: The string that you assigned to describe the webhook - :param unicode event_types: The array of events that this Webhook is subscribed to. - :param unicode webhook_url: The URL associated with this Webhook. - :param WebhookInstance.Status status: The webhook status + :param target_url: API-generated URL for the requested results page - :returns: The updated WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance + :returns: Page of WebhookInstance """ - return self._proxy.update( - friendly_name=friendly_name, - event_types=event_types, - webhook_url=webhook_url, - status=status, - ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) - def delete(self): + def get(self, sid: str) -> WebhookContext: """ - Deletes the WebhookInstance + Constructs a WebhookContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. """ - return self._proxy.delete() + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) - def fetch(self): + def __call__(self, sid: str) -> WebhookContext: """ - Fetch the WebhookInstance + Constructs a WebhookContext - :returns: The fetched WebhookInstance - :rtype: twilio.rest.verify.v2.service.webhook.WebhookInstance + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. """ - return self._proxy.fetch() + return WebhookContext( + 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/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 f9f1c1bde5..d57e4f1ecc 100644 --- a/twilio/rest/video/__init__.py +++ b/twilio/rest/video/__init__.py @@ -1,88 +1,65 @@ -# coding=utf-8 -r""" -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 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 - - @property - def compositions(self): - """ - :rtype: twilio.rest.video.v1.composition.CompositionList - """ + def compositions(self) -> CompositionList: + warn( + "compositions is deprecated. Use v1.compositions instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.compositions @property - def composition_hooks(self): - """ - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookList - """ + def composition_hooks(self) -> CompositionHookList: + warn( + "composition_hooks is deprecated. Use v1.composition_hooks instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.composition_hooks @property - def composition_settings(self): - """ - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList - """ + 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 recording_settings(self): - """ - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsList - """ + def recording_settings(self) -> RecordingSettingsList: + warn( + "recording_settings is deprecated. Use v1.recording_settings instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.recording_settings @property - def rooms(self): - """ - :rtype: twilio.rest.video.v1.room.RoomList - """ + def rooms(self) -> RoomList: + warn( + "rooms is deprecated. Use v1.rooms instead.", + DeprecationWarning, + stacklevel=2, + ) return self.v1.rooms - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/video/v1/__init__.py b/twilio/rest/video/v1/__init__.py index d238ca7446..0667596a3f 100644 --- a/twilio/rest/video/v1/__init__.py +++ b/twilio/rest/video/v1/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -17,81 +25,59 @@ 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 - """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._compositions = None - self._composition_hooks = None - self._composition_settings = None - self._recordings = None - self._recording_settings = None - self._rooms = None + :param domain: The Twilio.video domain + """ + super().__init__(domain, "v1") + self._compositions: Optional[CompositionList] = None + self._composition_hooks: Optional[CompositionHookList] = None + self._composition_settings: Optional[CompositionSettingsList] = None + self._recordings: Optional[RecordingList] = None + self._recording_settings: Optional[RecordingSettingsList] = None + self._rooms: Optional[RoomList] = None @property - def compositions(self): - """ - :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 composition_hooks(self): - """ - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookList - """ + 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): - """ - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList - """ + def composition_settings(self) -> CompositionSettingsList: if self._composition_settings is None: self._composition_settings = CompositionSettingsList(self) return self._composition_settings @property - def recordings(self): - """ - :rtype: twilio.rest.video.v1.recording.RecordingList - """ + def recordings(self) -> RecordingList: if self._recordings is None: self._recordings = RecordingList(self) return self._recordings @property - def recording_settings(self): - """ - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsList - """ + def recording_settings(self) -> RecordingSettingsList: if self._recording_settings is None: self._recording_settings = RecordingSettingsList(self) return self._recording_settings @property - def rooms(self): - """ - :rtype: twilio.rest.video.v1.room.RoomList - """ + 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 622f7f936d..0000000000 --- a/twilio/rest/video/v1/composition/__init__.py +++ /dev/null @@ -1,550 +0,0 @@ -# coding=utf-8 -r""" -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: Read only Composition resources with this status - :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 unicode room_sid: Read only Composition resources with this 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']) - - 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: Read only Composition resources with this status - :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 unicode room_sid: Read only Composition resources with this 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: Read only Composition resources with this status - :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 unicode room_sid: Read only Composition resources with this 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 - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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, room_sid, video_layout=values.unset, - audio_sources=values.unset, audio_sources_excluded=values.unset, - resolution=values.unset, format=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - trim=values.unset): - """ - Create the CompositionInstance - - :param unicode room_sid: The SID of the Group Room with the media tracks to be used as composition sources - :param dict video_layout: An object that describes the video layout of the composition - :param unicode audio_sources: An array of track names from the same group room to merge - :param unicode audio_sources_excluded: An array of track names to exclude - :param unicode resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels - :param CompositionInstance.Format format: The container format of the composition's media files - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param bool trim: Whether to clip the intervals where there is no active media in the composition - - :returns: The created CompositionInstance - :rtype: twilio.rest.video.v1.composition.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': trim, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return CompositionInstance(self._version, payload, ) - - def get(self, sid): - """ - Constructs a CompositionContext - - :param sid: The SID that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 the CompositionInstance - - :returns: The fetched CompositionInstance - :rtype: twilio.rest.video.v1.composition.CompositionInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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): - ENQUEUED = "enqueued" - PROCESSING = "processing" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - - class Format(object): - MP4 = "mp4" - WEBM = "webm" - - 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.get('account_sid'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_completed': deserialize.iso8601_datetime(payload.get('date_completed')), - 'date_deleted': deserialize.iso8601_datetime(payload.get('date_deleted')), - 'sid': payload.get('sid'), - 'room_sid': payload.get('room_sid'), - 'audio_sources': payload.get('audio_sources'), - 'audio_sources_excluded': payload.get('audio_sources_excluded'), - 'video_layout': payload.get('video_layout'), - 'resolution': payload.get('resolution'), - 'trim': payload.get('trim'), - 'format': payload.get('format'), - 'bitrate': deserialize.integer(payload.get('bitrate')), - 'size': deserialize.integer(payload.get('size')), - 'duration': deserialize.integer(payload.get('duration')), - 'url': payload.get('url'), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status of the composition - :rtype: CompositionInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_completed(self): - """ - :returns: Date when the media processing task finished - :rtype: datetime - """ - return self._properties['date_completed'] - - @property - def date_deleted(self): - """ - :returns: The ISO 8601 date and time in GMT when the composition generated media was deleted - :rtype: datetime - """ - return self._properties['date_deleted'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def room_sid(self): - """ - :returns: The SID of the Group Room that generated the audio and video tracks used in the composition - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def audio_sources(self): - """ - :returns: The array of track names to include in the composition - :rtype: unicode - """ - return self._properties['audio_sources'] - - @property - def audio_sources_excluded(self): - """ - :returns: The array of track names to exclude from the composition - :rtype: unicode - """ - return self._properties['audio_sources_excluded'] - - @property - def video_layout(self): - """ - :returns: An object that describes the video layout of the composition - :rtype: dict - """ - return self._properties['video_layout'] - - @property - def resolution(self): - """ - :returns: The dimensions of the video image in pixels expressed as columns (width) and rows (height) - :rtype: unicode - """ - return self._properties['resolution'] - - @property - def trim(self): - """ - :returns: Whether to remove intervals with no media - :rtype: bool - """ - return self._properties['trim'] - - @property - def format(self): - """ - :returns: The container format of the composition's media files as specified in the POST request that created the Composition resource - :rtype: CompositionInstance.Format - """ - return self._properties['format'] - - @property - def bitrate(self): - """ - :returns: The average bit rate of the composition's media - :rtype: unicode - """ - return self._properties['bitrate'] - - @property - def size(self): - """ - :returns: The size of the composed media file in bytes - :rtype: unicode - """ - return self._properties['size'] - - @property - def duration(self): - """ - :returns: The duration of the composition's media file in seconds - :rtype: unicode - """ - return self._properties['duration'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The URL of the media file associated with the composition - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch the CompositionInstance - - :returns: The 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 index f5470b929f..30fead17b0 100644 --- a/twilio/rest/video/v1/composition_hook.py +++ b/twilio/rest/video/v1/composition_hook.py @@ -1,590 +1,882 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 -class CompositionHookList(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 CompositionHookList +class CompositionHookInstance(InstanceResource): - :param Version version: Version that contains the resource + class Format(object): + MP4 = "mp4" + WEBM = "webm" - :returns: twilio.rest.video.v1.composition_hook.CompositionHookList - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookList - """ - super(CompositionHookList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/CompositionHooks'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CompositionHookContext] = None - def stream(self, enabled=values.unset, date_created_after=values.unset, - date_created_before=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + @property + def _proxy(self) -> "CompositionHookContext": """ - 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 datetime with time zone - :param datetime date_created_before: Read only CompositionHook resources created before this ISO 8601 datetime with time zone - :param unicode friendly_name: Read only CompositionHook resources with friendly names that match this string - :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.video.v1.composition_hook.CompositionHookInstance] + :returns: CompositionHookContext for this CompositionHookInstance """ - 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']) + if self._context is None: + self._context = CompositionHookContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, enabled=values.unset, date_created_after=values.unset, - date_created_before=values.unset, friendly_name=values.unset, - limit=None, page_size=None): + def delete(self) -> bool: """ - Lists CompositionHookInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + Deletes the CompositionHookInstance - :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 datetime with time zone - :param datetime date_created_before: Read only CompositionHook resources created before this ISO 8601 datetime with time zone - :param unicode friendly_name: Read only CompositionHook resources with friendly names that match this string - :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_hook.CompositionHookInstance] + :returns: True if delete succeeds, False otherwise """ - 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, - )) + return self._proxy.delete() - def page(self, enabled=values.unset, date_created_after=values.unset, - date_created_before=values.unset, 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 CompositionHookInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CompositionHookInstance - :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 datetime with time zone - :param datetime date_created_before: Read only CompositionHook resources created before this ISO 8601 datetime with time zone - :param unicode friendly_name: Read only CompositionHook resources with friendly names that match this string - :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 CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookPage + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Enabled': 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, - }) + return await self._proxy.delete_async() - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return CompositionHookPage(self._version, response, self._solution) - - def get_page(self, target_url): + def fetch(self) -> "CompositionHookInstance": """ - Retrieve a specific page of CompositionHookInstance records from the API. - Request is executed immediately + Fetch the CompositionHookInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookPage + :returns: The fetched CompositionHookInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - - return CompositionHookPage(self._version, response, self._solution) + return self._proxy.fetch() - def create(self, friendly_name, enabled=values.unset, video_layout=values.unset, - audio_sources=values.unset, audio_sources_excluded=values.unset, - resolution=values.unset, format=values.unset, - status_callback=values.unset, status_callback_method=values.unset, - trim=values.unset): + async def fetch_async(self) -> "CompositionHookInstance": """ - Create the CompositionHookInstance + Asynchronous coroutine to fetch the CompositionHookInstance - :param unicode friendly_name: A unique string to describe the resource - :param bool enabled: Whether the composition hook is active - :param dict video_layout: An object that describes the video layout of the composition hook - :param unicode audio_sources: An array of track names from the same group room to merge - :param unicode audio_sources_excluded: An array of track names to exclude - :param unicode resolution: A string that describes the rows (width) and columns (height) of the generated composed video in pixels - :param CompositionHookInstance.Format format: The container format of the media files used by the compositions created by the composition hook - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param bool trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook - :returns: The created CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + :returns: The fetched CompositionHookInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Enabled': 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': trim, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return CompositionHookInstance(self._version, payload, ) - - def get(self, sid): + 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": """ - Constructs a CompositionHookContext - - :param sid: The SID that identifies the resource to fetch + Update the CompositionHookInstance - :returns: twilio.rest.video.v1.composition_hook.CompositionHookContext - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext - """ - return CompositionHookContext(self._version, sid=sid, ) + :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`. - def __call__(self, sid): + :returns: The updated CompositionHookInstance """ - Constructs a CompositionHookContext + 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, + ) - :param sid: The SID that identifies the resource to fetch + 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: twilio.rest.video.v1.composition_hook.CompositionHookContext - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext + :returns: The updated CompositionHookInstance """ - return CompositionHookContext(self._version, sid=sid, ) + 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): + 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 CompositionHookPage(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 CompositionHookContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the CompositionHookPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the CompositionHookContext - :returns: twilio.rest.video.v1.composition_hook.CompositionHookPage - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookPage + :param version: Version that contains the resource + :param sid: The SID of the CompositionHook resource to update. """ - super(CompositionHookPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/CompositionHooks/{sid}".format(**self._solution) - def get_instance(self, payload): + def delete(self) -> bool: """ - Build an instance of CompositionHookInstance + Deletes the CompositionHookInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.video.v1.composition_hook.CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + :returns: True if delete succeeds, False otherwise """ - return CompositionHookInstance(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 CompositionHookInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class CompositionHookContext(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) -> CompositionHookInstance: """ - Initialize the CompositionHookContext + Fetch the CompositionHookInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.video.v1.composition_hook.CompositionHookContext - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext + :returns: The fetched CompositionHookInstance """ - super(CompositionHookContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/CompositionHooks/{sid}'.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 CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CompositionHookInstance: """ - Fetch the CompositionHookInstance + Asynchronous coroutine to fetch the CompositionHookInstance + :returns: The fetched CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return CompositionHookInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - def delete(self): - """ - Deletes the CompositionHookInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def update(self, friendly_name, enabled=values.unset, video_layout=values.unset, - audio_sources=values.unset, audio_sources_excluded=values.unset, - trim=values.unset, format=values.unset, resolution=values.unset, - status_callback=values.unset, status_callback_method=values.unset): + 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 unicode friendly_name: A unique string to describe the resource - :param bool enabled: Whether the composition hook is active - :param dict video_layout: A JSON object that describes the video layout of the composition hook - :param unicode audio_sources: An array of track names from the same group room to merge - :param unicode audio_sources_excluded: An array of track names to exclude - :param bool trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook - :param CompositionHookInstance.Format format: The container format of the media files used by the compositions created by the composition hook - :param unicode resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback + :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 - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Enabled': enabled, - 'VideoLayout': serialize.object(video_layout), - 'AudioSources': serialize.map(audio_sources, lambda e: e), - 'AudioSourcesExcluded': serialize.map(audio_sources_excluded, lambda e: e), - 'Trim': trim, - 'Format': format, - 'Resolution': resolution, - 'StatusCallback': status_callback, - 'StatusCallbackMethod': status_callback_method, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return CompositionHookInstance(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 + 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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({}) -class CompositionHookInstance(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["Content-Type"] = "application/x-www-form-urlencoded" - class Format(object): - MP4 = "mp4" - WEBM = "webm" + headers["Accept"] = "application/json" - def __init__(self, version, payload, sid=None): - """ - Initialize the CompositionHookInstance - - :returns: twilio.rest.video.v1.composition_hook.CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance - """ - super(CompositionHookInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'enabled': payload.get('enabled'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'sid': payload.get('sid'), - 'audio_sources': payload.get('audio_sources'), - 'audio_sources_excluded': payload.get('audio_sources_excluded'), - 'video_layout': payload.get('video_layout'), - 'resolution': payload.get('resolution'), - 'trim': payload.get('trim'), - 'format': payload.get('format'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'url': payload.get('url'), - } + 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 CompositionHookInstance( + self._version, payload, sid=self._solution["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: CompositionHookContext for this CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = CompositionHookContext(self._version, sid=self._solution['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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] +class CompositionHookPage(Page): - @property - def enabled(self): - """ - :returns: Whether the CompositionHook is active - :rtype: bool + def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: """ - return self._properties['enabled'] + Build an instance of CompositionHookInstance - @property - def date_created(self): + :param payload: Payload response from the API """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + return CompositionHookInstance(self._version, payload) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime + def __repr__(self) -> str: """ - return self._properties['date_updated'] + Provide a friendly representation - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['sid'] + return "" - @property - def audio_sources(self): - """ - :returns: The array of track names to include in the compositions created by the composition hook - :rtype: unicode - """ - return self._properties['audio_sources'] - @property - def audio_sources_excluded(self): - """ - :returns: The array of track names to exclude from the compositions created by the composition hook - :rtype: unicode - """ - return self._properties['audio_sources_excluded'] +class CompositionHookList(ListResource): - @property - def video_layout(self): + def __init__(self, version: Version): """ - :returns: A JSON object that describes the video layout of the Composition - :rtype: dict + Initialize the CompositionHookList + + :param version: Version that contains the resource + """ - return self._properties['video_layout'] + super().__init__(version) - @property - def resolution(self): + 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: """ - :returns: The dimensions of the video image in pixels expressed as columns (width) and rows (height) - :rtype: unicode + 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 """ - return self._properties['resolution'] - @property - def trim(self): + 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 """ - :returns: Whether intervals with no media are clipped - :rtype: bool + + 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]: """ - return self._properties['trim'] + 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. - @property - def format(self): + :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 """ - :returns: The container format of the media files used by the compositions created by the composition hook - :rtype: CompositionHookInstance.Format + 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]: """ - return self._properties['format'] + 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. - @property - def status_callback(self): + :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 """ - :returns: The URL to send status information to your application - :rtype: unicode + 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]: """ - return self._properties['status_callback'] + Lists CompositionHookInstance 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_callback_method(self): + :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: """ - :returns: The HTTP method we should use to call status_callback - :rtype: unicode + 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 """ - return self._properties['status_callback_method'] + 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, + } + ) - @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 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 """ - :returns: The absolute URL of the resource - :rtype: unicode + 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: """ - return self._properties['url'] + Retrieve a specific page of CompositionHookInstance 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 CompositionHookInstance """ - Fetch the CompositionHookInstance + response = self._version.domain.twilio.request("GET", target_url) + return CompositionHookPage(self._version, response) - :returns: The fetched CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + async def get_page_async(self, target_url: str) -> CompositionHookPage: """ - return self._proxy.fetch() + 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 - def delete(self): + :returns: Page of CompositionHookInstance """ - Deletes the CompositionHookInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return CompositionHookPage(self._version, response) - :returns: True if delete succeeds, False otherwise - :rtype: bool + def get(self, sid: str) -> CompositionHookContext: """ - return self._proxy.delete() + Constructs a CompositionHookContext - def update(self, friendly_name, enabled=values.unset, video_layout=values.unset, - audio_sources=values.unset, audio_sources_excluded=values.unset, - trim=values.unset, format=values.unset, resolution=values.unset, - status_callback=values.unset, status_callback_method=values.unset): + :param sid: The SID of the CompositionHook resource to update. """ - Update the CompositionHookInstance + return CompositionHookContext(self._version, sid=sid) - :param unicode friendly_name: A unique string to describe the resource - :param bool enabled: Whether the composition hook is active - :param dict video_layout: A JSON object that describes the video layout of the composition hook - :param unicode audio_sources: An array of track names from the same group room to merge - :param unicode audio_sources_excluded: An array of track names to exclude - :param bool trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook - :param CompositionHookInstance.Format format: The container format of the media files used by the compositions created by the composition hook - :param unicode resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels - :param unicode status_callback: The URL we should call to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback + def __call__(self, sid: str) -> CompositionHookContext: + """ + Constructs a CompositionHookContext - :returns: The updated CompositionHookInstance - :rtype: twilio.rest.video.v1.composition_hook.CompositionHookInstance + :param sid: The SID of the CompositionHook resource to update. """ - return self._proxy.update( - 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, - ) + return CompositionHookContext(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/composition_settings.py b/twilio/rest/video/v1/composition_settings.py index 034489274f..384ae692e8 100644 --- a/twilio/rest/video/v1/composition_settings.py +++ b/twilio/rest/video/v1/composition_settings.py @@ -1,316 +1,318 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 values +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 CompositionSettingsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version): - """ - Initialize the CompositionSettingsList - :param Version version: Version that contains the resource +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 - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsList - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList + @property + def _proxy(self) -> "CompositionSettingsContext": """ - super(CompositionSettingsList, self).__init__(version) - - # Path Solution - 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 get(self): + :returns: CompositionSettingsContext for this CompositionSettingsInstance """ - Constructs a CompositionSettingsContext + if self._context is None: + self._context = CompositionSettingsContext( + self._version, + ) + return self._context - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext + 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": """ - return CompositionSettingsContext(self._version, ) + Create the CompositionSettingsInstance - def __call__(self): - """ - Constructs a CompositionSettingsContext + :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: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext + :returns: The created CompositionSettingsInstance """ - return CompositionSettingsContext(self._version, ) + 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, + ) - def __repr__(self): - """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :returns: The created CompositionSettingsInstance """ - return '' - - -class CompositionSettingsPage(Page): - """ """ + 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 __init__(self, version, response, solution): + def fetch(self) -> "CompositionSettingsInstance": """ - Initialize the CompositionSettingsPage + Fetch the CompositionSettingsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsPage - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsPage + :returns: The fetched CompositionSettingsInstance """ - super(CompositionSettingsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch() - def get_instance(self, payload): + async def fetch_async(self) -> "CompositionSettingsInstance": """ - Build an instance of CompositionSettingsInstance + Asynchronous coroutine to fetch the CompositionSettingsInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance + :returns: The fetched CompositionSettingsInstance """ - return CompositionSettingsInstance(self._version, payload, ) + return await self._proxy.fetch_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class CompositionSettingsContext(InstanceContext): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the CompositionSettingsContext - :param Version version: Version that contains the resource - - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext + :param version: Version that contains the resource """ - super(CompositionSettingsContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/CompositionSettings/Default'.format(**self._solution) + self._uri = "/CompositionSettings/Default" - def fetch(self): + 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: """ - Fetch the CompositionSettingsInstance + Create the CompositionSettingsInstance - :returns: The fetched CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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, ) + return CompositionSettingsInstance(self._version, payload) - def create(self, friendly_name, aws_credentials_sid=values.unset, - encryption_key_sid=values.unset, aws_s3_url=values.unset, - aws_storage_enabled=values.unset, encryption_enabled=values.unset): + 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: """ - Create the CompositionSettingsInstance + Asynchronous coroutine to create the CompositionSettingsInstance - :param unicode friendly_name: A descriptive string that you create to describe the resource - :param unicode aws_credentials_sid: The SID of the stored Credential resource - :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption - :param unicode aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored - :param bool aws_storage_enabled: Whether all compositions should be written to the aws_s3_url - :param bool encryption_enabled: Whether all compositions should be stored in an encrypted form + :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 - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'AwsCredentialsSid': aws_credentials_sid, - 'EncryptionKeySid': encryption_key_sid, - 'AwsS3Url': aws_s3_url, - 'AwsStorageEnabled': aws_storage_enabled, - 'EncryptionEnabled': encryption_enabled, - }) + 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, ) + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) - return CompositionSettingsInstance(self._version, payload, ) + return CompositionSettingsInstance(self._version, payload) - def __repr__(self): + def fetch(self) -> CompositionSettingsInstance: """ - Provide a friendly representation + Fetch the CompositionSettingsInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched CompositionSettingsInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class CompositionSettingsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload): + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> CompositionSettingsInstance: """ - Initialize the CompositionSettingsInstance + Asynchronous coroutine to fetch the CompositionSettingsInstance + - :returns: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance + :returns: The fetched CompositionSettingsInstance """ - super(CompositionSettingsInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'aws_credentials_sid': payload.get('aws_credentials_sid'), - 'aws_s3_url': payload.get('aws_s3_url'), - 'aws_storage_enabled': payload.get('aws_storage_enabled'), - 'encryption_key_sid': payload.get('encryption_key_sid'), - 'encryption_enabled': payload.get('encryption_enabled'), - 'url': payload.get('url'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {} + 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.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: CompositionSettingsContext for this CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsContext - """ - if self._context is None: - self._context = CompositionSettingsContext(self._version, ) - return self._context + return CompositionSettingsInstance( + self._version, + payload, + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['friendly_name'] - @property - def aws_credentials_sid(self): - """ - :returns: The SID of the stored Credential resource - :rtype: unicode - """ - return self._properties['aws_credentials_sid'] + return "" - @property - def aws_s3_url(self): - """ - :returns: The URL of the AWS S3 bucket where the compositions are stored - :rtype: unicode - """ - return self._properties['aws_s3_url'] - @property - def aws_storage_enabled(self): - """ - :returns: Whether all compositions are written to the aws_s3_url - :rtype: bool - """ - return self._properties['aws_storage_enabled'] +class CompositionSettingsList(ListResource): - @property - def encryption_key_sid(self): + def __init__(self, version: Version): """ - :returns: The SID of the Public Key resource used for encryption - :rtype: unicode - """ - return self._properties['encryption_key_sid'] + Initialize the CompositionSettingsList - @property - def encryption_enabled(self): - """ - :returns: Whether all compositions are stored in an encrypted form - :rtype: bool - """ - return self._properties['encryption_enabled'] + :param version: Version that contains the resource - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + super().__init__(version) - def fetch(self): + def get(self) -> CompositionSettingsContext: """ - Fetch the CompositionSettingsInstance + Constructs a CompositionSettingsContext - :returns: The fetched CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ - return self._proxy.fetch() + return CompositionSettingsContext(self._version) - def create(self, friendly_name, aws_credentials_sid=values.unset, - encryption_key_sid=values.unset, aws_s3_url=values.unset, - aws_storage_enabled=values.unset, encryption_enabled=values.unset): + def __call__(self) -> CompositionSettingsContext: """ - Create the CompositionSettingsInstance - - :param unicode friendly_name: A descriptive string that you create to describe the resource - :param unicode aws_credentials_sid: The SID of the stored Credential resource - :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption - :param unicode aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored - :param bool aws_storage_enabled: Whether all compositions should be written to the aws_s3_url - :param bool encryption_enabled: Whether all compositions should be stored in an encrypted form + Constructs a CompositionSettingsContext - :returns: The created CompositionSettingsInstance - :rtype: twilio.rest.video.v1.composition_settings.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, - ) + return CompositionSettingsContext(self._version) - 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/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 61ccc11947..0000000000 --- a/twilio/rest/video/v1/recording/__init__.py +++ /dev/null @@ -1,503 +0,0 @@ -# coding=utf-8 -r""" -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, media_type=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: Read only the recordings that have this status - :param unicode source_sid: Read only the recordings that have this source_sid - :param unicode grouping_sid: Read only recordings that have this grouping_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 - :param RecordingInstance.Type media_type: Read only recordings that have this media 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.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, - media_type=media_type, - page_size=limits['page_size'], - ) - - return self._version.stream(page, limits['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, media_type=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: Read only the recordings that have this status - :param unicode source_sid: Read only the recordings that have this source_sid - :param unicode grouping_sid: Read only recordings that have this grouping_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 - :param RecordingInstance.Type media_type: Read only recordings that have this media 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.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, - media_type=media_type, - 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, media_type=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: Read only the recordings that have this status - :param unicode source_sid: Read only the recordings that have this source_sid - :param unicode grouping_sid: Read only recordings that have this grouping_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 - :param RecordingInstance.Type media_type: Read only recordings that have this media 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 RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingPage - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 the RecordingInstance - - :returns: The fetched RecordingInstance - :rtype: twilio.rest.video.v1.recording.RecordingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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(method='DELETE', uri=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.get('account_sid'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'sid': payload.get('sid'), - 'source_sid': payload.get('source_sid'), - 'size': deserialize.integer(payload.get('size')), - 'url': payload.get('url'), - 'type': payload.get('type'), - 'duration': deserialize.integer(payload.get('duration')), - 'container_format': payload.get('container_format'), - 'codec': payload.get('codec'), - 'grouping_sids': payload.get('grouping_sids'), - 'track_name': payload.get('track_name'), - 'offset': deserialize.integer(payload.get('offset')), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status of the recording - :rtype: RecordingInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def source_sid(self): - """ - :returns: The SID of the recording source - :rtype: unicode - """ - return self._properties['source_sid'] - - @property - def size(self): - """ - :returns: The size of the recorded track, in bytes - :rtype: unicode - """ - return self._properties['size'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def type(self): - """ - :returns: The recording's media type - :rtype: RecordingInstance.Type - """ - return self._properties['type'] - - @property - def duration(self): - """ - :returns: The duration of the recording in seconds - :rtype: unicode - """ - return self._properties['duration'] - - @property - def container_format(self): - """ - :returns: The file format for the recording - :rtype: RecordingInstance.Format - """ - return self._properties['container_format'] - - @property - def codec(self): - """ - :returns: The codec used to encode the track - :rtype: RecordingInstance.Codec - """ - return self._properties['codec'] - - @property - def grouping_sids(self): - """ - :returns: A list of SIDs related to the recording - :rtype: dict - """ - return self._properties['grouping_sids'] - - @property - def track_name(self): - """ - :returns: The name that was given to the source track of the recording - :rtype: unicode - """ - return self._properties['track_name'] - - @property - def offset(self): - """ - :returns: The number of milliseconds between a point in time that is common to all rooms in a group and when the source room of the recording started - :rtype: unicode - """ - return self._properties['offset'] - - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch the RecordingInstance - - :returns: The 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 index ca87eea917..46259b6cf8 100644 --- a/twilio/rest/video/v1/recording_settings.py +++ b/twilio/rest/video/v1/recording_settings.py @@ -1,316 +1,318 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 values +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 RecordingSettingsList(ListResource): - """ """ +from twilio.base.version import Version - def __init__(self, version): - """ - Initialize the RecordingSettingsList - :param Version version: Version that contains the resource +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 - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsList - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsList + @property + def _proxy(self) -> "RecordingSettingsContext": """ - super(RecordingSettingsList, self).__init__(version) - - # Path Solution - 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 get(self): + :returns: RecordingSettingsContext for this RecordingSettingsInstance """ - Constructs a RecordingSettingsContext + if self._context is None: + self._context = RecordingSettingsContext( + self._version, + ) + return self._context - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext + 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": """ - return RecordingSettingsContext(self._version, ) + Create the RecordingSettingsInstance - def __call__(self): - """ - Constructs a RecordingSettingsContext + :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: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext + :returns: The created RecordingSettingsInstance """ - return RecordingSettingsContext(self._version, ) + 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, + ) - def __repr__(self): - """ - Provide a friendly representation + 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: Machine friendly representation - :rtype: str + :returns: The created RecordingSettingsInstance """ - return '' - - -class RecordingSettingsPage(Page): - """ """ + 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 __init__(self, version, response, solution): + def fetch(self) -> "RecordingSettingsInstance": """ - Initialize the RecordingSettingsPage + Fetch the RecordingSettingsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsPage - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsPage + :returns: The fetched RecordingSettingsInstance """ - super(RecordingSettingsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + return self._proxy.fetch() - def get_instance(self, payload): + async def fetch_async(self) -> "RecordingSettingsInstance": """ - Build an instance of RecordingSettingsInstance + Asynchronous coroutine to fetch the RecordingSettingsInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance + :returns: The fetched RecordingSettingsInstance """ - return RecordingSettingsInstance(self._version, payload, ) + return await self._proxy.fetch_async() - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class RecordingSettingsContext(InstanceContext): - """ """ - def __init__(self, version): + def __init__(self, version: Version): """ Initialize the RecordingSettingsContext - :param Version version: Version that contains the resource - - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext + :param version: Version that contains the resource """ - super(RecordingSettingsContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/RecordingSettings/Default'.format(**self._solution) + self._uri = "/RecordingSettings/Default" - def fetch(self): + 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: """ - Fetch the RecordingSettingsInstance + Create the RecordingSettingsInstance - :returns: The fetched RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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, ) + return RecordingSettingsInstance(self._version, payload) - def create(self, friendly_name, aws_credentials_sid=values.unset, - encryption_key_sid=values.unset, aws_s3_url=values.unset, - aws_storage_enabled=values.unset, encryption_enabled=values.unset): + 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: """ - Create the RecordingSettingsInstance + Asynchronous coroutine to create the RecordingSettingsInstance - :param unicode friendly_name: A string to describe the resource - :param unicode aws_credentials_sid: The SID of the stored Credential resource - :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption - :param unicode aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored - :param bool aws_storage_enabled: Whether all recordings should be written to the aws_s3_url - :param bool encryption_enabled: Whether all recordings should be stored in an encrypted form + :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 - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'AwsCredentialsSid': aws_credentials_sid, - 'EncryptionKeySid': encryption_key_sid, - 'AwsS3Url': aws_s3_url, - 'AwsStorageEnabled': aws_storage_enabled, - 'EncryptionEnabled': encryption_enabled, - }) + 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, ) + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) - return RecordingSettingsInstance(self._version, payload, ) + return RecordingSettingsInstance(self._version, payload) - def __repr__(self): + def fetch(self) -> RecordingSettingsInstance: """ - Provide a friendly representation + Fetch the RecordingSettingsInstance - :returns: Machine friendly representation - :rtype: str + + :returns: The fetched RecordingSettingsInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + headers = values.of({}) -class RecordingSettingsInstance(InstanceResource): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, payload): + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> RecordingSettingsInstance: """ - Initialize the RecordingSettingsInstance + Asynchronous coroutine to fetch the RecordingSettingsInstance + - :returns: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance + :returns: The fetched RecordingSettingsInstance """ - super(RecordingSettingsInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'aws_credentials_sid': payload.get('aws_credentials_sid'), - 'aws_s3_url': payload.get('aws_s3_url'), - 'aws_storage_enabled': payload.get('aws_storage_enabled'), - 'encryption_key_sid': payload.get('encryption_key_sid'), - 'encryption_enabled': payload.get('encryption_enabled'), - 'url': payload.get('url'), - } + headers = values.of({}) - # Context - self._context = None - self._solution = {} + 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.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: RecordingSettingsContext for this RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext - """ - if self._context is None: - self._context = RecordingSettingsContext(self._version, ) - return self._context + return RecordingSettingsInstance( + self._version, + payload, + ) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['friendly_name'] - @property - def aws_credentials_sid(self): - """ - :returns: The SID of the stored Credential resource - :rtype: unicode - """ - return self._properties['aws_credentials_sid'] + return "" - @property - def aws_s3_url(self): - """ - :returns: The URL of the AWS S3 bucket where the recordings are stored - :rtype: unicode - """ - return self._properties['aws_s3_url'] - @property - def aws_storage_enabled(self): - """ - :returns: Whether all recordings are written to the aws_s3_url - :rtype: bool - """ - return self._properties['aws_storage_enabled'] +class RecordingSettingsList(ListResource): - @property - def encryption_key_sid(self): + def __init__(self, version: Version): """ - :returns: The SID of the Public Key resource used for encryption - :rtype: unicode - """ - return self._properties['encryption_key_sid'] + Initialize the RecordingSettingsList - @property - def encryption_enabled(self): - """ - :returns: Whether all recordings are stored in an encrypted form - :rtype: bool - """ - return self._properties['encryption_enabled'] + :param version: Version that contains the resource - @property - def url(self): """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] + super().__init__(version) - def fetch(self): + def get(self) -> RecordingSettingsContext: """ - Fetch the RecordingSettingsInstance + Constructs a RecordingSettingsContext - :returns: The fetched RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsInstance """ - return self._proxy.fetch() + return RecordingSettingsContext(self._version) - def create(self, friendly_name, aws_credentials_sid=values.unset, - encryption_key_sid=values.unset, aws_s3_url=values.unset, - aws_storage_enabled=values.unset, encryption_enabled=values.unset): + def __call__(self) -> RecordingSettingsContext: """ - Create the RecordingSettingsInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode aws_credentials_sid: The SID of the stored Credential resource - :param unicode encryption_key_sid: The SID of the Public Key resource to use for encryption - :param unicode aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored - :param bool aws_storage_enabled: Whether all recordings should be written to the aws_s3_url - :param bool encryption_enabled: Whether all recordings should be stored in an encrypted form + Constructs a RecordingSettingsContext - :returns: The created RecordingSettingsInstance - :rtype: twilio.rest.video.v1.recording_settings.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, - ) + return RecordingSettingsContext(self._version) - 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/__init__.py b/twilio/rest/video/v1/room/__init__.py index 5e7b6f807d..d51b8b8711 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -1,603 +1,867 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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) + class VideoCodec(object): + VP8 = "VP8" + H264 = "H264" - 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 the RoomInstance + """ + :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") - :param bool enable_turn: Enable Twilio's Network Traversal TURN service - :param RoomInstance.RoomType type: The type of room - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode status_callback: The URL to send status information to your application - :param unicode status_callback_method: The HTTP method we should use to call status_callback - :param unicode max_participants: The maximum number of concurrent Participants allowed in the room - :param bool record_participants_on_connect: Whether to start recording when Participants connect - :param RoomInstance.VideoCodec video_codecs: An array of the video codecs that are supported when publishing a track in the room - :param unicode media_region: The region for the media server in Group Rooms + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoomContext] = None - :returns: The created RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + @property + def _proxy(self) -> "RoomContext": """ - 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - - return RoomInstance(self._version, payload, ) + 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, status=values.unset, unique_name=values.unset, - date_created_after=values.unset, date_created_before=values.unset, - limit=None, page_size=None): + :returns: RoomContext for this RoomInstance """ - Streams RoomInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param RoomInstance.RoomStatus status: Read only the rooms with this status - :param unicode unique_name: Read only rooms with 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 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 = 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']) + :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: Read only the rooms with this status - :param unicode unique_name: Read only rooms with 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 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 + Update the RoomInstance - :param RoomInstance.RoomStatus status: Read only the rooms with this status - :param unicode unique_name: Read only rooms with 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 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 status: - :returns: Page of RoomInstance - :rtype: twilio.rest.video.v1.room.RoomPage + :returns: The updated RoomInstance """ - data = values.of({ - 'Status': status, - 'UniqueName': unique_name, - 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), - 'DateCreatedBefore': serialize.iso8601_datetime(date_created_before), - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RoomPage(self._version, response, self._solution) + return self._proxy.update( + status=status, + ) - 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 that identifies the resource to fetch - - :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 that identifies the resource to fetch + 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 + self._solution = { + "sid": sid, + } + self._uri = "/Rooms/{sid}".format(**self._solution) - def get_instance(self, payload): + self._participants: Optional[ParticipantList] = None + self._recording_rules: Optional[RecordingRulesList] = None + self._recordings: Optional[RoomRecordingList] = None + + def fetch(self) -> RoomInstance: """ - Build an instance of RoomInstance + Fetch the RoomInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.video.v1.room.RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance + :returns: The fetched RoomInstance """ - return RoomInstance(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 RoomContext(InstanceContext): - """ """ + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> RoomInstance: """ - Initialize the RoomContext + Asynchronous coroutine to fetch the RoomInstance - :param Version version: Version that contains the resource - :param sid: The SID that identifies the resource to fetch - :returns: twilio.rest.video.v1.room.RoomContext - :rtype: twilio.rest.video.v1.room.RoomContext + :returns: The fetched RoomInstance """ - super(RoomContext, self).__init__(version) - - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Rooms/{sid}'.format(**self._solution) - # Dependents - self._recordings = None - self._participants = None + headers = values.of({}) - def fetch(self): - """ - Fetch the RoomInstance + headers["Accept"] = "application/json" - :returns: The fetched RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 new status of the resource + :param status: :returns: The updated RoomInstance - :rtype: twilio.rest.video.v1.room.RoomInstance """ - data = values.of({'Status': status, }) - payload = self._version.update(method='POST', uri=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) + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) -class RoomInstance(InstanceResource): - """ """ - - class RoomStatus(object): - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" + headers["Content-Type"] = "application/x-www-form-urlencoded" - class RoomType(object): - PEER_TO_PEER = "peer-to-peer" - GROUP = "group" - GROUP_SMALL = "group-small" + headers["Accept"] = "application/json" - class VideoCodec(object): - VP8 = "VP8" - H264 = "H264" - - 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.get('sid'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'account_sid': payload.get('account_sid'), - 'enable_turn': payload.get('enable_turn'), - 'unique_name': payload.get('unique_name'), - 'status_callback': payload.get('status_callback'), - 'status_callback_method': payload.get('status_callback_method'), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'duration': deserialize.integer(payload.get('duration')), - 'type': payload.get('type'), - 'max_participants': deserialize.integer(payload.get('max_participants')), - 'record_participants_on_connect': payload.get('record_participants_on_connect'), - 'video_codecs': payload.get('video_codecs'), - 'media_region': payload.get('media_region'), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :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 of the room - :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 ISO 8601 date and time in GMT when the 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 ISO 8601 date and time in GMT when the 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 account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - @property - def enable_turn(self): - """ - :returns: Enable Twilio's Network Traversal TURN service - :rtype: bool - """ - return self._properties['enable_turn'] +class RoomPage(Page): - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :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 URL to send status information to your application - :rtype: unicode - """ - return self._properties['status_callback'] + return RoomInstance(self._version, payload) - @property - def status_callback_method(self): + def __repr__(self) -> str: """ - :returns: The HTTP method we use to call status_callback - :rtype: unicode - """ - return self._properties['status_callback_method'] + Provide a friendly representation - @property - def end_time(self): - """ - :returns: The UTC end time of the room in UTC ISO 8601 format - :rtype: datetime + :returns: Machine friendly representation """ - return self._properties['end_time'] + return "" - @property - def duration(self): - """ - :returns: The duration of the room in seconds - :rtype: unicode - """ - return self._properties['duration'] - @property - def type(self): - """ - :returns: The type of room - :rtype: RoomInstance.RoomType - """ - return self._properties['type'] +class RoomList(ListResource): - @property - def max_participants(self): + def __init__(self, version: Version): """ - :returns: The maximum number of concurrent Participants allowed in the room - :rtype: unicode + Initialize the RoomList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Rooms" + + def create( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: """ - return self._properties['max_participants'] + Create the RoomInstance - @property - def record_participants_on_connect(self): + :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 """ - :returns: Whether to start recording when Participants connect - :rtype: bool + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload) + + async def create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Asynchronously create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance """ - return self._properties['record_participants_on_connect'] - @property - def video_codecs(self): + 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: An array of the video codecs that are supported when publishing a track in the room - :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 region for the media server in Group Rooms - :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 absolute URL of the resource - :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 URLs of related resources - :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"}) - def fetch(self): + 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: """ - Fetch the RoomInstance + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately - :returns: The 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 new status of the resource + :param target_url: API-generated URL for the requested results page - :returns: The 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 1f09b9b84d..0000000000 --- a/twilio/rest/video/v1/room/recording/__init__.py +++ /dev/null @@ -1,509 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Room resource the recording is associated with - - :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: Read only the recordings with this status - :param unicode 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 datetime with time zone - :param datetime date_created_before: Read only Recordings that started before this ISO 8601 date-time with time zone - :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']) - - 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: Read only the recordings with this status - :param unicode 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 datetime with time zone - :param datetime date_created_before: Read only Recordings that started before this ISO 8601 date-time with time zone - :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: Read only the recordings with this status - :param unicode 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 datetime with time zone - :param datetime date_created_before: Read only Recordings that started before this ISO 8601 date-time with time zone - :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 - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 SID of the Room resource the recording is associated with - - :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 SID of the Room resource with the recording to fetch - :param sid: The SID that identifies the resource to fetch - - :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 the RoomRecordingInstance - - :returns: The fetched RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return RoomRecordingInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - sid=self._solution['sid'], - ) - - def delete(self): - """ - Deletes the RoomRecordingInstance - - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 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.get('account_sid'), - 'status': payload.get('status'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'sid': payload.get('sid'), - 'source_sid': payload.get('source_sid'), - 'size': deserialize.integer(payload.get('size')), - 'url': payload.get('url'), - 'type': payload.get('type'), - 'duration': deserialize.integer(payload.get('duration')), - 'container_format': payload.get('container_format'), - 'codec': payload.get('codec'), - 'grouping_sids': payload.get('grouping_sids'), - 'track_name': payload.get('track_name'), - 'offset': deserialize.integer(payload.get('offset')), - 'room_sid': payload.get('room_sid'), - 'links': payload.get('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 SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status of the recording - :rtype: RoomRecordingInstance.Status - """ - return self._properties['status'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def source_sid(self): - """ - :returns: The SID of the recording source - :rtype: unicode - """ - return self._properties['source_sid'] - - @property - def size(self): - """ - :returns: The size of the recorded track in bytes - :rtype: unicode - """ - return self._properties['size'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def type(self): - """ - :returns: The recording's media type - :rtype: RoomRecordingInstance.Type - """ - return self._properties['type'] - - @property - def duration(self): - """ - :returns: The duration of the recording in seconds - :rtype: unicode - """ - return self._properties['duration'] - - @property - def container_format(self): - """ - :returns: The file format for the recording - :rtype: RoomRecordingInstance.Format - """ - return self._properties['container_format'] - - @property - def codec(self): - """ - :returns: The codec used for the recording - :rtype: RoomRecordingInstance.Codec - """ - return self._properties['codec'] - - @property - def grouping_sids(self): - """ - :returns: A list of SIDs related to the Recording - :rtype: dict - """ - return self._properties['grouping_sids'] - - @property - def track_name(self): - """ - :returns: The name that was given to the source track of the recording - :rtype: unicode - """ - return self._properties['track_name'] - - @property - def offset(self): - """ - :returns: The number of milliseconds between a point in time that is common to all rooms in a group and when the source room of the recording started - :rtype: unicode - """ - return self._properties['offset'] - - @property - def room_sid(self): - """ - :returns: The SID of the Room resource the recording is associated with - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch the RoomRecordingInstance - - :returns: The fetched RoomRecordingInstance - :rtype: twilio.rest.video.v1.room.recording.RoomRecordingInstance - """ - return self._proxy.fetch() - - def delete(self): - """ - Deletes the RoomRecordingInstance - - :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/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 10257df46e..0000000000 --- a/twilio/rest/video/v1/room/room_participant/__init__.py +++ /dev/null @@ -1,555 +0,0 @@ -# coding=utf-8 -r""" -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_subscribe_rule import SubscribeRulesList -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 SID of the participant's room - - :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: Read only the participants with this status - :param unicode identity: Read only the Participants with this user identity value - :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format - :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format - :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']) - - 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: Read only the participants with this status - :param unicode identity: Read only the Participants with this user identity value - :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format - :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format - :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: Read only the participants with this status - :param unicode identity: Read only the Participants with this user identity value - :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format - :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format - :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 - """ - 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, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 SID of the participant's room - - :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 SID of the room with the Participant resource to fetch - :param sid: The SID that identifies the resource to fetch - - :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 - self._subscribe_rules = None - - def fetch(self): - """ - Fetch the ParticipantInstance - - :returns: The fetched ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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 new status of the resource - - :returns: The updated ParticipantInstance - :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance - """ - data = values.of({'Status': status, }) - - payload = self._version.update(method='POST', uri=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'], - participant_sid=self._solution['sid'], - ) - return self._subscribed_tracks - - @property - def subscribe_rules(self): - """ - Access the subscribe_rules - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - """ - if self._subscribe_rules is None: - self._subscribe_rules = SubscribeRulesList( - self._version, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['sid'], - ) - return self._subscribe_rules - - 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.get('sid'), - 'room_sid': payload.get('room_sid'), - 'account_sid': payload.get('account_sid'), - 'status': payload.get('status'), - 'identity': payload.get('identity'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), - 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), - 'duration': deserialize.integer(payload.get('duration')), - 'url': payload.get('url'), - 'links': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def room_sid(self): - """ - :returns: The SID of the participant's room - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] - - @property - def status(self): - """ - :returns: The status of the Participant - :rtype: ParticipantInstance.Status - """ - return self._properties['status'] - - @property - def identity(self): - """ - :returns: The string that identifies the resource's User - :rtype: unicode - """ - return self._properties['identity'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def start_time(self): - """ - :returns: The time of participant connected to the room in ISO 8601 format - :rtype: datetime - """ - return self._properties['start_time'] - - @property - def end_time(self): - """ - :returns: The time when the participant disconnected from the room in ISO 8601 format - :rtype: datetime - """ - return self._properties['end_time'] - - @property - def duration(self): - """ - :returns: Duration of time in seconds the participant was connected - :rtype: unicode - """ - return self._properties['duration'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - @property - def links(self): - """ - :returns: The URLs of related resources - :rtype: unicode - """ - return self._properties['links'] - - def fetch(self): - """ - Fetch the ParticipantInstance - - :returns: The 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 new status of the resource - - :returns: The 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 - - @property - def subscribe_rules(self): - """ - Access the subscribe_rules - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - """ - return self._proxy.subscribe_rules - - 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 f883d952f7..0000000000 --- a/twilio/rest/video/v1/room/room_participant/room_participant_published_track.py +++ /dev/null @@ -1,396 +0,0 @@ -# coding=utf-8 -r""" -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 SID of the Room resource where the track is published - :param participant_sid: The SID of the Participant resource with the published track - - :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']) - - 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 - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 that identifies the resource to fetch - - :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 that identifies the resource to fetch - - :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 SID of the Room resource where the track is published - :param participant_sid: The SID of the Participant resource with the published track - - :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 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 that identifies the resource to fetch - - :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 the PublishedTrackInstance - - :returns: The fetched PublishedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - 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.get('sid'), - 'participant_sid': payload.get('participant_sid'), - 'room_sid': payload.get('room_sid'), - 'name': payload.get('name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'enabled': payload.get('enabled'), - 'kind': payload.get('kind'), - 'url': payload.get('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 unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def participant_sid(self): - """ - :returns: The SID of the Participant resource with the published track - :rtype: unicode - """ - return self._properties['participant_sid'] - - @property - def room_sid(self): - """ - :returns: The SID of the Room resource where the track is published - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def name(self): - """ - :returns: The track name - :rtype: unicode - """ - return self._properties['name'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def enabled(self): - """ - :returns: Whether the track is enabled - :rtype: bool - """ - return self._properties['enabled'] - - @property - def kind(self): - """ - :returns: The track type - :rtype: PublishedTrackInstance.Kind - """ - return self._properties['kind'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the PublishedTrackInstance - - :returns: The 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_subscribe_rule.py b/twilio/rest/video/v1/room/room_participant/room_participant_subscribe_rule.py deleted file mode 100644 index 4369337824..0000000000 --- a/twilio/rest/video/v1/room/room_participant/room_participant_subscribe_rule.py +++ /dev/null @@ -1,204 +0,0 @@ -# coding=utf-8 -r""" -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 SubscribeRulesList(ListResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, room_sid, participant_sid): - """ - Initialize the SubscribeRulesList - - :param Version version: Version that contains the resource - :param room_sid: The SID of the Room resource for the Subscribe Rules - :param participant_sid: The SID of the Participant resource for the Subscribe Rules - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList - """ - super(SubscribeRulesList, self).__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): - """ - Fetch the SubscribeRulesInstance - - :returns: The fetched SubscribeRulesInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SubscribeRulesInstance( - self._version, - payload, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - ) - - def update(self, rules=values.unset): - """ - Update the SubscribeRulesInstance - - :param dict rules: A JSON-encoded array of subscribe rules - - :returns: The updated SubscribeRulesInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - """ - data = values.of({'Rules': serialize.object(rules), }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SubscribeRulesInstance( - 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 SubscribeRulesPage(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 SubscribeRulesPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param room_sid: The SID of the Room resource for the Subscribe Rules - :param participant_sid: The SID of the Participant resource for the Subscribe Rules - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesPage - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesPage - """ - super(SubscribeRulesPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of SubscribeRulesInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - """ - return SubscribeRulesInstance( - 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 SubscribeRulesInstance(InstanceResource): - """ PLEASE NOTE that this class contains beta products that are subject to - change. Use them with caution. """ - - def __init__(self, version, payload, room_sid, participant_sid): - """ - Initialize the SubscribeRulesInstance - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesInstance - """ - super(SubscribeRulesInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'participant_sid': payload.get('participant_sid'), - 'room_sid': payload.get('room_sid'), - 'rules': payload.get('rules'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - } - - # Context - self._context = None - self._solution = {'room_sid': room_sid, 'participant_sid': participant_sid, } - - @property - def participant_sid(self): - """ - :returns: The SID of the Participant resource for the Subscribe Rules - :rtype: unicode - """ - return self._properties['participant_sid'] - - @property - def room_sid(self): - """ - :returns: The SID of the Room resource for the Subscribe Rules - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def rules(self): - """ - :returns: A collection of Subscribe Rules that describe how to include or exclude matching tracks - :rtype: unicode - """ - return self._properties['rules'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last 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/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 5d5c801cbb..0000000000 --- a/twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py +++ /dev/null @@ -1,405 +0,0 @@ -# coding=utf-8 -r""" -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 SubscribedTrackList(ListResource): - """ """ - - def __init__(self, version, room_sid, participant_sid): - """ - Initialize the SubscribedTrackList - - :param Version version: Version that contains the resource - :param room_sid: The SID of the room where the track is published - :param participant_sid: The SID of the participant that subscribes to the track - - :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, 'participant_sid': participant_sid, } - self._uri = '/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks'.format(**self._solution) - - def stream(self, 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 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(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) - - def list(self, 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 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(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 SubscribedTrackInstance 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 SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage - """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - 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 get(self, sid): - """ - Constructs a SubscribedTrackContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - """ - return SubscribedTrackContext( - self._version, - room_sid=self._solution['room_sid'], - participant_sid=self._solution['participant_sid'], - sid=sid, - ) - - def __call__(self, sid): - """ - Constructs a SubscribedTrackContext - - :param sid: The SID that identifies the resource to fetch - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - """ - return SubscribedTrackContext( - 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 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 SID of the room where the track is published - :param participant_sid: The SID of the participant that subscribes to the track - - :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'], - participant_sid=self._solution['participant_sid'], - ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class SubscribedTrackContext(InstanceContext): - """ """ - - def __init__(self, version, room_sid, participant_sid, sid): - """ - Initialize the SubscribedTrackContext - - :param Version 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 that identifies the resource to fetch - - :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - """ - super(SubscribedTrackContext, 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}/SubscribedTracks/{sid}'.format(**self._solution) - - def fetch(self): - """ - Fetch the SubscribedTrackInstance - - :returns: The fetched SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - - return SubscribedTrackInstance( - 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 SubscribedTrackInstance(InstanceResource): - """ """ - - class Kind(object): - AUDIO = "audio" - VIDEO = "video" - DATA = "data" - - def __init__(self, version, payload, room_sid, participant_sid, sid=None): - """ - 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.get('sid'), - 'participant_sid': payload.get('participant_sid'), - 'publisher_sid': payload.get('publisher_sid'), - 'room_sid': payload.get('room_sid'), - 'name': payload.get('name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'enabled': payload.get('enabled'), - 'kind': payload.get('kind'), - 'url': payload.get('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: SubscribedTrackContext for this SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext - """ - 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 - - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - - @property - def participant_sid(self): - """ - :returns: The SID of the participant that subscribes to the track - :rtype: unicode - """ - return self._properties['participant_sid'] - - @property - def publisher_sid(self): - """ - :returns: The SID of the participant that publishes the track - :rtype: unicode - """ - return self._properties['publisher_sid'] - - @property - def room_sid(self): - """ - :returns: The SID of the room where the track is published - :rtype: unicode - """ - return self._properties['room_sid'] - - @property - def name(self): - """ - :returns: The track name - :rtype: unicode - """ - return self._properties['name'] - - @property - def date_created(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] - - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] - - @property - def enabled(self): - """ - :returns: Whether the track is enabled - :rtype: bool - """ - return self._properties['enabled'] - - @property - def kind(self): - """ - :returns: The track type - :rtype: SubscribedTrackInstance.Kind - """ - return self._properties['kind'] - - @property - def url(self): - """ - :returns: The absolute URL of the resource - :rtype: unicode - """ - return self._properties['url'] - - def fetch(self): - """ - Fetch the SubscribedTrackInstance - - :returns: The fetched SubscribedTrackInstance - :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance - """ - 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_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 index 269262da42..019a3a2058 100644 --- a/twilio/rest/voice/__init__.py +++ b/twilio/rest/voice/__init__.py @@ -1,81 +1,65 @@ -# coding=utf-8 -r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / -""" +from warnings import warn -from twilio.base.domain import Domain -from twilio.rest.voice.v1 import V1 +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(Domain): - - def __init__(self, twilio): - """ - Initialize the Voice Domain - - :returns: Domain for Voice - :rtype: twilio.rest.voice.Voice - """ - super(Voice, self).__init__(twilio) - - self.base_url = 'https://voice.twilio.com' - - # Versions - self._v1 = None - +class Voice(VoiceBase): @property - def v1(self): - """ - :returns: Version v1 of voice - :rtype: twilio.rest.voice.v1.V1 - """ - if self._v1 is None: - self._v1 = V1(self) - return self._v1 + 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): - """ - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.ip_record.IpRecordList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingList - """ + 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 - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' diff --git a/twilio/rest/voice/v1/__init__.py b/twilio/rest/voice/v1/__init__.py index 45b977e4c3..75c0c7fc74 100644 --- a/twilio/rest/voice/v1/__init__.py +++ b/twilio/rest/voice/v1/__init__.py @@ -1,12 +1,21 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -16,71 +25,59 @@ class V1(Version): - def __init__(self, domain): + def __init__(self, domain: Domain): """ Initialize the V1 version of Voice - :returns: V1 version of Voice - :rtype: twilio.rest.voice.v1.V1.V1 + :param domain: The Twilio.voice domain """ - super(V1, self).__init__(domain) - self.version = 'v1' - self._byoc_trunks = None - self._connection_policies = None - self._dialing_permissions = None - self._ip_records = None - self._source_ip_mappings = None + 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 byoc_trunks(self): - """ - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.ip_record.IpRecordList - """ + 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): - """ - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingList - """ + 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): + def __repr__(self) -> str: """ Provide a friendly representation - :returns: Machine friendly representation - :rtype: str """ - return '' + 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 index 1d52c8d647..304bdd78a5 100644 --- a/twilio/rest/voice/v1/byoc_trunk.py +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -1,543 +1,787 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 ByocTrunkList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the ByocTrunkList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ByocTrunkContext] = None - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkList - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkList + @property + def _proxy(self) -> "ByocTrunkContext": """ - super(ByocTrunkList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/ByocTrunks'.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, voice_url=values.unset, - voice_method=values.unset, voice_fallback_url=values.unset, - voice_fallback_method=values.unset, status_callback_url=values.unset, - status_callback_method=values.unset, - cnam_lookup_enabled=values.unset, connection_policy_sid=values.unset, - from_domain_sid=values.unset): + :returns: ByocTrunkContext for this ByocTrunkInstance """ - Create the ByocTrunkInstance - - :param unicode friendly_name: A string to describe the resource - :param unicode voice_url: The URL we should call when receiving a call - :param unicode voice_method: The HTTP method to use with voice_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_fallback_method: The HTTP method to use with voice_fallback_url - :param unicode status_callback_url: The URL that we should call to pass status updates - :param unicode status_callback_method: The HTTP method we should use to call `status_callback_url` - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :param unicode connection_policy_sid: Origination Connection Policy (to your Carrier) - :param unicode from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls + if self._context is None: + self._context = ByocTrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance + def delete(self) -> bool: """ - 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': cnam_lookup_enabled, - 'ConnectionPolicySid': connection_policy_sid, - 'FromDomainSid': from_domain_sid, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Deletes the ByocTrunkInstance - return ByocTrunkInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 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.voice.v1.byoc_trunk.ByocTrunkInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ByocTrunkInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch the ByocTrunkInstance - :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.voice.v1.byoc_trunk.ByocTrunkInstance] + :returns: The fetched ByocTrunkInstance """ - 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) -> "ByocTrunkInstance": """ - Retrieve a single page of ByocTrunkInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ByocTrunkInstance - :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 ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkPage + :returns: The fetched ByocTrunkInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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 - return ByocTrunkPage(self._version, response, self._solution) + :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\\\". - def get_page(self, target_url): + :returns: The updated ByocTrunkInstance """ - Retrieve a specific page of ByocTrunkInstance records from the API. - Request is executed immediately + 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, + ) - :param str target_url: API-generated URL for the requested results page + 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: Page of ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkPage + :returns: The updated ByocTrunkInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + 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, ) - return ByocTrunkPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a ByocTrunkContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext +class ByocTrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return ByocTrunkContext(self._version, sid=sid, ) + Initialize the ByocTrunkContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. """ - Constructs a ByocTrunkContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ByocTrunks/{sid}".format(**self._solution) - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext + def delete(self) -> bool: """ - return ByocTrunkContext(self._version, sid=sid, ) + Deletes the ByocTrunkInstance - 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 ByocTrunkPage(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 ByocTrunkPage + Asynchronous coroutine that deletes the ByocTrunkInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkPage - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkPage + :returns: True if delete succeeds, False otherwise """ - super(ByocTrunkPage, 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) -> ByocTrunkInstance: """ - Build an instance of ByocTrunkInstance + Fetch the ByocTrunkInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance + :returns: The fetched ByocTrunkInstance """ - return ByocTrunkInstance(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 ByocTrunkContext(InstanceContext): - """ """ + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> ByocTrunkInstance: """ - Initialize the ByocTrunkContext + Asynchronous coroutine to fetch the ByocTrunkInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext + :returns: The fetched ByocTrunkInstance """ - super(ByocTrunkContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/ByocTrunks/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the ByocTrunkInstance + headers["Accept"] = "application/json" - :returns: The fetched ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - return ByocTrunkInstance(self._version, payload, sid=self._solution['sid'], ) + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset, voice_url=values.unset, - voice_method=values.unset, voice_fallback_url=values.unset, - voice_fallback_method=values.unset, status_callback_url=values.unset, - status_callback_method=values.unset, - cnam_lookup_enabled=values.unset, connection_policy_sid=values.unset, - from_domain_sid=values.unset): + 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 unicode friendly_name: A string to describe the resource - :param unicode voice_url: The URL we should call when receiving a call - :param unicode voice_method: The HTTP method we should use with voice_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode status_callback_url: The URL that we should call to pass status updates - :param unicode status_callback_method: The HTTP method we should use to call status_callback_url - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :param unicode connection_policy_sid: Origination Connection Policy (to your Carrier) - :param unicode from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls + :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 - :rtype: twilio.rest.voice.v1.byoc_trunk.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': cnam_lookup_enabled, - 'ConnectionPolicySid': connection_policy_sid, - 'FromDomainSid': from_domain_sid, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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({}) - return ByocTrunkInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the ByocTrunkInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool + 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 """ - return self._version.delete(method='DELETE', uri=self._uri, ) - def __repr__(self): + 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 - :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 ByocTrunkInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, sid=None): - """ - Initialize the ByocTrunkInstance - - :returns: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance - """ - super(ByocTrunkInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'voice_url': payload.get('voice_url'), - 'voice_method': payload.get('voice_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'status_callback_url': payload.get('status_callback_url'), - 'status_callback_method': payload.get('status_callback_method'), - 'cnam_lookup_enabled': payload.get('cnam_lookup_enabled'), - 'connection_policy_sid': payload.get('connection_policy_sid'), - 'from_domain_sid': payload.get('from_domain_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } - - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } +class ByocTrunkPage(Page): - @property - def _proxy(self): + def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: """ - 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 ByocTrunkInstance - :returns: ByocTrunkContext for this ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkContext + :param payload: Payload response from the API """ - if self._context is None: - self._context = ByocTrunkContext(self._version, sid=self._solution['sid'], ) - return self._context + return ByocTrunkInstance(self._version, payload) - @property - def account_sid(self): + def __repr__(self) -> str: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + Provide a friendly representation - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['sid'] + return "" - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] - @property - def voice_url(self): - """ - :returns: The URL we call when receiving a call - :rtype: unicode - """ - return self._properties['voice_url'] +class ByocTrunkList(ListResource): - @property - def voice_method(self): - """ - :returns: The HTTP method to use with voice_url - :rtype: unicode + def __init__(self, version: Version): """ - return self._properties['voice_method'] + Initialize the ByocTrunkList - @property - def voice_fallback_url(self): - """ - :returns: The URL we call when an error occurs while executing TwiML - :rtype: unicode - """ - return self._properties['voice_fallback_url'] + :param version: Version that contains the resource - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method used with voice_fallback_url - :rtype: unicode """ - return self._properties['voice_fallback_method'] + super().__init__(version) - @property - def status_callback_url(self): - """ - :returns: The URL that we call with status updates - :rtype: unicode + 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: """ - return self._properties['status_callback_url'] + Create the ByocTrunkInstance - @property - def status_callback_method(self): + :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 """ - :returns: The HTTP method we use to call status_callback_url - :rtype: unicode + + 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 """ - return self._properties['status_callback_method'] - @property - def cnam_lookup_enabled(self): + 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]: """ - :returns: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :rtype: bool + 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 """ - return self._properties['cnam_lookup_enabled'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def connection_policy_sid(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ByocTrunkInstance]: """ - :returns: Origination Connection Policy (to your Carrier) - :rtype: unicode + 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 """ - return self._properties['connection_policy_sid'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def from_domain_sid(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: """ - :returns: The SID of the SIP Domain that should be used in the `From` header of originating calls - :rtype: unicode + 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 self._properties['from_domain_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[ByocTrunkInstance]: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of ByocTrunkInstance 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 ByocTrunkInstance """ - :returns: The RFC 2822 date and time in GMT that the resource was last 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 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of ByocTrunkInstance 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 ByocTrunkInstance """ - :returns: The absolute URL of the 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 ByocTrunkPage(self._version, response) + + def get_page(self, target_url: str) -> ByocTrunkPage: """ - return self._properties['url'] + Retrieve a specific page of ByocTrunkInstance 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 ByocTrunkInstance """ - Fetch the ByocTrunkInstance + response = self._version.domain.twilio.request("GET", target_url) + return ByocTrunkPage(self._version, response) - :returns: The fetched ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance + async def get_page_async(self, target_url: str) -> ByocTrunkPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, voice_url=values.unset, - voice_method=values.unset, voice_fallback_url=values.unset, - voice_fallback_method=values.unset, status_callback_url=values.unset, - status_callback_method=values.unset, - cnam_lookup_enabled=values.unset, connection_policy_sid=values.unset, - from_domain_sid=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance """ - Update the ByocTrunkInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ByocTrunkPage(self._version, response) - :param unicode friendly_name: A string to describe the resource - :param unicode voice_url: The URL we should call when receiving a call - :param unicode voice_method: The HTTP method we should use with voice_url - :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML - :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url - :param unicode status_callback_url: The URL that we should call to pass status updates - :param unicode status_callback_method: The HTTP method we should use to call status_callback_url - :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk - :param unicode connection_policy_sid: Origination Connection Policy (to your Carrier) - :param unicode from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls + def get(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext - :returns: The updated ByocTrunkInstance - :rtype: twilio.rest.voice.v1.byoc_trunk.ByocTrunkInstance + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. """ - 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, - ) + return ByocTrunkContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> ByocTrunkContext: """ - Deletes the ByocTrunkInstance + Constructs a ByocTrunkContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. """ - return self._proxy.delete() + return ByocTrunkContext(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/voice/v1/connection_policy/__init__.py b/twilio/rest/voice/v1/connection_policy/__init__.py index faa5a3a727..e2a56929c7 100644 --- a/twilio/rest/voice/v1/connection_policy/__init__.py +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -1,425 +1,629 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.voice.v1.connection_policy.connection_policy_target import ConnectionPolicyTargetList +from twilio.rest.voice.v1.connection_policy.connection_policy_target import ( + ConnectionPolicyTargetList, +) -class ConnectionPolicyList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the ConnectionPolicyList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyContext] = None - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyList + @property + def _proxy(self) -> "ConnectionPolicyContext": """ - super(ConnectionPolicyList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/ConnectionPolicies'.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): + :returns: ConnectionPolicyContext for this ConnectionPolicyInstance """ - Create the ConnectionPolicyInstance - - :param unicode friendly_name: A string to describe the resource + if self._context is None: + self._context = ConnectionPolicyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: The created ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance + def delete(self) -> bool: """ - data = values.of({'FriendlyName': friendly_name, }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + Deletes the ConnectionPolicyInstance - return ConnectionPolicyInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 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.voice.v1.connection_policy.ConnectionPolicyInstance] + async def delete_async(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Asynchronous coroutine that deletes the ConnectionPolicyInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['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) -> "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. + Fetch the ConnectionPolicyInstance - :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.voice.v1.connection_policy.ConnectionPolicyInstance] + :returns: The fetched ConnectionPolicyInstance """ - 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) -> "ConnectionPolicyInstance": """ - Retrieve a single page of ConnectionPolicyInstance records from the API. - Request is executed immediately + Asynchronous coroutine to fetch the ConnectionPolicyInstance - :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 ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage + :returns: The fetched ConnectionPolicyInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return ConnectionPolicyPage(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 + ) -> "ConnectionPolicyInstance": """ - Retrieve a specific page of ConnectionPolicyInstance records from the API. - Request is executed immediately + Update the ConnectionPolicyInstance - :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 is not unique and can be up to 255 characters long. - :returns: Page of ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage + :returns: The updated ConnectionPolicyInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return self._proxy.update( + friendly_name=friendly_name, ) - return ConnectionPolicyPage(self._version, response, self._solution) - - def get(self, sid): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": """ - Constructs a ConnectionPolicyContext + Asynchronous coroutine to update the ConnectionPolicyInstance - :param sid: The unique string that identifies the resource + :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: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext + :returns: The updated ConnectionPolicyInstance """ - return ConnectionPolicyContext(self._version, sid=sid, ) + return await self._proxy.update_async( + friendly_name=friendly_name, + ) - def __call__(self, sid): + @property + def targets(self) -> ConnectionPolicyTargetList: """ - Constructs a ConnectionPolicyContext - - :param sid: The unique string that identifies the resource - - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext + Access the targets """ - return ConnectionPolicyContext(self._version, sid=sid, ) + return self._proxy.targets - 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 ConnectionPolicyPage(Page): - """ """ +class ConnectionPolicyContext(InstanceContext): - def __init__(self, version, response, solution): + def __init__(self, version: Version, sid: str): """ - Initialize the ConnectionPolicyPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API + Initialize the ConnectionPolicyContext - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyPage + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Connection Policy resource to update. """ - super(ConnectionPolicyPage, self).__init__(version, response) + super().__init__(version) # Path Solution - self._solution = solution + self._solution = { + "sid": sid, + } + self._uri = "/ConnectionPolicies/{sid}".format(**self._solution) - def get_instance(self, payload): + self._targets: Optional[ConnectionPolicyTargetList] = None + + def delete(self) -> bool: """ - Build an instance of ConnectionPolicyInstance + Deletes the ConnectionPolicyInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance + :returns: True if delete succeeds, False otherwise """ - return ConnectionPolicyInstance(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 ConnectionPolicyInstance - :returns: Machine friendly representation - :rtype: str + + :returns: True if delete succeeds, False otherwise """ - return '' + headers = values.of({}) -class ConnectionPolicyContext(InstanceContext): - """ """ + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def __init__(self, version, sid): + def fetch(self) -> ConnectionPolicyInstance: """ - Initialize the ConnectionPolicyContext + Fetch the ConnectionPolicyInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext + :returns: The fetched ConnectionPolicyInstance """ - super(ConnectionPolicyContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/ConnectionPolicies/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._targets = None + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def fetch(self): + async def fetch_async(self) -> ConnectionPolicyInstance: """ - Fetch the ConnectionPolicyInstance + Asynchronous coroutine to fetch the ConnectionPolicyInstance + :returns: The fetched ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return ConnectionPolicyInstance(self._version, payload, sid=self._solution['sid'], ) + 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=values.unset): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: """ Update the ConnectionPolicyInstance - :param unicode friendly_name: A string to describe the resource + :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 - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ConnectionPolicyInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - def delete(self): + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: """ - Deletes the ConnectionPolicyInstance + Asynchronous coroutine to update the ConnectionPolicyInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=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 ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) @property - def targets(self): + def targets(self) -> ConnectionPolicyTargetList: """ Access the targets - - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList """ if self._targets is None: self._targets = ConnectionPolicyTargetList( self._version, - connection_policy_sid=self._solution['sid'], + self._solution["sid"], ) return self._targets - 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 ConnectionPolicyInstance(InstanceResource): - """ """ +class ConnectionPolicyPage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: """ - Initialize the ConnectionPolicyInstance + Build an instance of ConnectionPolicyInstance - :returns: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance + :param payload: Payload response from the API """ - super(ConnectionPolicyInstance, self).__init__(version) + return ConnectionPolicyInstance(self._version, payload) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: Machine friendly representation + """ + return "" - @property - def _proxy(self): + +class ConnectionPolicyList(ListResource): + + 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 ConnectionPolicyList + + :param version: Version that contains the resource - :returns: ConnectionPolicyContext for this ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyContext """ - if self._context is None: - self._context = ConnectionPolicyContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def account_sid(self): + self._uri = "/ConnectionPolicies" + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def 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 ConnectionPolicyInstance(self._version, payload) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 """ - return self._properties['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 ConnectionPolicyInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyInstance]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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 """ - 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[ConnectionPolicyInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime + 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 """ - 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[ConnectionPolicyInstance]: """ - :returns: The RFC 2822 date and time in GMT when the resource was last updated - :rtype: datetime + 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 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[ConnectionPolicyInstance]: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 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, + ) -> ConnectionPolicyPage: """ - :returns: The URLs of related resources - :rtype: unicode + 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 """ - return self._properties['links'] + data = values.of( + { + "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 = 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: """ - Fetch the ConnectionPolicyInstance + Asynchronously retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately - :returns: The fetched ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance + :param page_token: PageToken provided by the API + :param page_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 """ - 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 ConnectionPolicyPage(self._version, response) - def update(self, friendly_name=values.unset): + def get_page(self, target_url: str) -> ConnectionPolicyPage: """ - Update the ConnectionPolicyInstance + Retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately - :param unicode friendly_name: A string to describe the resource + :param target_url: API-generated URL for the requested results page - :returns: The updated ConnectionPolicyInstance - :rtype: twilio.rest.voice.v1.connection_policy.ConnectionPolicyInstance + :returns: Page of ConnectionPolicyInstance """ - return self._proxy.update(friendly_name=friendly_name, ) + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyPage(self._version, response) - def delete(self): + async def get_page_async(self, target_url: str) -> ConnectionPolicyPage: """ - Deletes the ConnectionPolicyInstance + Asynchronously retrieve a specific page of ConnectionPolicyInstance 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 ConnectionPolicyInstance """ - return self._proxy.delete() + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyPage(self._version, response) - @property - def targets(self): + def get(self, sid: str) -> ConnectionPolicyContext: """ - Access the targets + Constructs a ConnectionPolicyContext - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList + :param sid: The unique string that we created to identify the Connection Policy resource to update. """ - return self._proxy.targets + 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): + 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/voice/v1/connection_policy/connection_policy_target.py b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py index 967cb50dfa..03f4fd607d 100644 --- a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -1,501 +1,736 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 ConnectionPolicyTargetList(ListResource): - """ """ +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") - def __init__(self, version, connection_policy_sid): + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyTargetContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyTargetContext": """ - Initialize the ConnectionPolicyTargetList + 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 connection_policy_sid: The SID of the Connection Policy that owns the Target + :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 - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetList + def delete(self) -> bool: """ - super(ConnectionPolicyTargetList, self).__init__(version) + Deletes the ConnectionPolicyTargetInstance - # Path Solution - self._solution = {'connection_policy_sid': connection_policy_sid, } - self._uri = '/ConnectionPolicies/{connection_policy_sid}/Targets'.format(**self._solution) - def create(self, target, friendly_name=values.unset, priority=values.unset, - weight=values.unset, enabled=values.unset): + :returns: True if delete succeeds, False otherwise """ - Create the ConnectionPolicyTargetInstance + return self._proxy.delete() - :param unicode target: The SIP address you want Twilio to route your calls to - :param unicode friendly_name: A string to describe the resource - :param unicode priority: The relative importance of the target - :param unicode weight: The value that determines the relative load the Target should receive compared to others with the same priority - :param bool enabled: Whether the Target is enabled + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance - :returns: The created ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance + + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'Target': target, - 'FriendlyName': friendly_name, - 'Priority': priority, - 'Weight': weight, - 'Enabled': enabled, - }) + return await self._proxy.delete_async() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + def fetch(self) -> "ConnectionPolicyTargetInstance": + """ + Fetch the ConnectionPolicyTargetInstance - return ConnectionPolicyTargetInstance( - self._version, - payload, - connection_policy_sid=self._solution['connection_policy_sid'], - ) - def stream(self, limit=None, page_size=None): + :returns: The fetched 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. + return self._proxy.fetch() - :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) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance] + + :returns: The fetched ConnectionPolicyTargetInstance """ - limits = self._version.read_limits(limit, page_size) + return await self._proxy.fetch_async() - page = self.page(page_size=limits['page_size'], ) + 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 - return self._version.stream(page, limits['limit']) + :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. - def list(self, limit=None, page_size=None): + :returns: The updated 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. + return self._proxy.update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=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) + 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 - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.connection_policy.connection_policy_target.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: """ - 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 ConnectionPolicyTargetInstance 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 ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetPage +class ConnectionPolicyTargetContext(InstanceContext): + + def __init__(self, version: Version, connection_policy_sid: str, sid: str): """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + Initialize the ConnectionPolicyTargetContext - response = self._version.page(method='GET', uri=self._uri, params=data, ) + :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) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets/{sid}".format( + **self._solution + ) - def get_page(self, target_url): + def delete(self) -> bool: """ - Retrieve a specific page of ConnectionPolicyTargetInstance records from the API. - Request is executed immediately + Deletes the ConnectionPolicyTargetInstance - :param str target_url: API-generated URL for the requested results page - :returns: Page of ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetPage + :returns: True if delete succeeds, False otherwise """ - response = self._version.domain.twilio.request( - 'GET', - target_url, - ) - return ConnectionPolicyTargetPage(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 ConnectionPolicyTargetContext + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext + :returns: True if delete succeeds, False otherwise """ - return ConnectionPolicyTargetContext( + + 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, - connection_policy_sid=self._solution['connection_policy_sid'], - sid=sid, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], ) - def __call__(self, sid): + async def fetch_async(self) -> ConnectionPolicyTargetInstance: """ - Constructs a ConnectionPolicyTargetContext + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext + :returns: The fetched ConnectionPolicyTargetInstance """ - return ConnectionPolicyTargetContext( + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectionPolicyTargetInstance( self._version, - connection_policy_sid=self._solution['connection_policy_sid'], - sid=sid, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], ) - def __repr__(self): + 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: """ - Provide a friendly representation + Update the ConnectionPolicyTargetInstance - :returns: Machine friendly representation - :rtype: str + :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 '' + 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" -class ConnectionPolicyTargetPage(Page): - """ """ + headers["Accept"] = "application/json" - def __init__(self, version, response, solution): + 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: """ - Initialize the ConnectionPolicyTargetPage + Asynchronous coroutine to update the ConnectionPolicyTargetInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param connection_policy_sid: The SID of the Connection Policy that owns the Target + :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: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetPage - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetPage + :returns: The updated ConnectionPolicyTargetInstance """ - super(ConnectionPolicyTargetPage, self).__init__(version, response) - # Path Solution - self._solution = solution + 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 get_instance(self, payload): + def __repr__(self) -> str: """ - Build an instance of ConnectionPolicyTargetInstance + 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 +class ConnectionPolicyTargetPage(Page): - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance + 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'], + connection_policy_sid=self._solution["connection_policy_sid"], ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class ConnectionPolicyTargetContext(InstanceContext): - """ """ +class ConnectionPolicyTargetList(ListResource): - def __init__(self, version, connection_policy_sid, sid): + def __init__(self, version: Version, connection_policy_sid: str): """ - Initialize the ConnectionPolicyTargetContext + Initialize the ConnectionPolicyTargetList - :param Version 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 identifies the resource + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy from which to read the Targets. - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext """ - super(ConnectionPolicyTargetContext, self).__init__(version) + 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) + self._solution = { + "connection_policy_sid": connection_policy_sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets".format( + **self._solution + ) - def fetch(self): + 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: """ - Fetch the ConnectionPolicyTargetInstance + Create the ConnectionPolicyTargetInstance - :returns: The fetched ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + + 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'], - sid=self._solution['sid'], + connection_policy_sid=self._solution["connection_policy_sid"], ) - def update(self, friendly_name=values.unset, target=values.unset, - priority=values.unset, weight=values.unset, enabled=values.unset): + 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: """ - Update the ConnectionPolicyTargetInstance + Asynchronously create the ConnectionPolicyTargetInstance - :param unicode friendly_name: A string to describe the resource - :param unicode target: The SIP address you want Twilio to route your calls to - :param unicode priority: The relative importance of the target - :param unicode weight: The value that determines the relative load the Target should receive compared to others with the same priority - :param bool enabled: Whether the Target is enabled + :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 updated ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance + :returns: The created ConnectionPolicyTargetInstance """ - data = values.of({ - 'FriendlyName': friendly_name, - 'Target': target, - 'Priority': priority, - 'Weight': weight, - 'Enabled': enabled, - }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], - sid=self._solution['sid'], + connection_policy_sid=self._solution["connection_policy_sid"], ) - def delete(self): + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyTargetInstance]: """ - Deletes the 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. - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=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 + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyTargetInstance]: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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) -class ConnectionPolicyTargetInstance(InstanceResource): - """ """ - - def __init__(self, version, payload, connection_policy_sid, sid=None): - """ - Initialize the ConnectionPolicyTargetInstance - - :returns: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance - """ - super(ConnectionPolicyTargetInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'connection_policy_sid': payload.get('connection_policy_sid'), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'target': payload.get('target'), - 'priority': deserialize.integer(payload.get('priority')), - 'weight': deserialize.integer(payload.get('weight')), - 'enabled': payload.get('enabled'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + :returns: Generator that 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 = { - 'connection_policy_sid': connection_policy_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[ConnectionPolicyTargetInstance]: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. - :returns: ConnectionPolicyTargetContext for this ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetContext + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt 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 = ConnectionPolicyTargetContext( - self._version, - connection_policy_sid=self._solution['connection_policy_sid'], - sid=self._solution['sid'], + return list( + self.stream( + limit=limit, + page_size=page_size, ) - return self._context + ) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: """ - return self._properties['account_sid'] + 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. - @property - def connection_policy_sid(self): - """ - :returns: The SID of the Connection Policy that owns the Target - :rtype: unicode - """ - return self._properties['connection_policy_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 sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode + :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 friendly_name(self): - """ - :returns: The string that you assigned to describe the resource - :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, + ) -> ConnectionPolicyTargetPage: """ - return self._properties['friendly_name'] + Retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately - @property - def target(self): - """ - :returns: The SIP address you want Twilio to route your calls to - :rtype: unicode - """ - return self._properties['target'] + :param page_token: PageToken provided by the 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 priority(self): - """ - :returns: The relative importance of the target - :rtype: unicode + :returns: Page of ConnectionPolicyTargetInstance """ - return self._properties['priority'] + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - @property - def weight(self): - """ - :returns: The value that determines the relative load the Target should receive compared to others with the same priority - :rtype: unicode - """ - return self._properties['weight'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def enabled(self): - """ - :returns: Whether the target is enabled - :rtype: bool - """ - return self._properties['enabled'] + headers["Accept"] = "application/json" - @property - def date_created(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage(self._version, response, self._solution) - @property - def date_updated(self): - """ - :returns: The RFC 2822 date and time in GMT when the resource was last 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, + ) -> ConnectionPolicyTargetPage: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of ConnectionPolicyTargetInstance 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 ConnectionPolicyTargetInstance """ - :returns: The absolute URL of the 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 ConnectionPolicyTargetPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: """ - return self._properties['url'] + 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 - def fetch(self): + :returns: Page of ConnectionPolicyTargetInstance """ - Fetch the ConnectionPolicyTargetInstance + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) - :returns: The fetched ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance + async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: """ - return self._proxy.fetch() + Asynchronously retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately - def update(self, friendly_name=values.unset, target=values.unset, - priority=values.unset, weight=values.unset, enabled=values.unset): + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance """ - Update the ConnectionPolicyTargetInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) - :param unicode friendly_name: A string to describe the resource - :param unicode target: The SIP address you want Twilio to route your calls to - :param unicode priority: The relative importance of the target - :param unicode weight: The value that determines the relative load the Target should receive compared to others with the same priority - :param bool enabled: Whether the Target is enabled + def get(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext - :returns: The updated ConnectionPolicyTargetInstance - :rtype: twilio.rest.voice.v1.connection_policy.connection_policy_target.ConnectionPolicyTargetInstance + :param sid: The unique string that we created to identify the Target resource to update. """ - return self._proxy.update( - friendly_name=friendly_name, - target=target, - priority=priority, - weight=weight, - enabled=enabled, + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, ) - def delete(self): + def __call__(self, sid: str) -> ConnectionPolicyTargetContext: """ - Deletes the ConnectionPolicyTargetInstance + Constructs a ConnectionPolicyTargetContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The unique string that we created to identify the Target resource to update. """ - return self._proxy.delete() + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_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/voice/v1/dialing_permissions/__init__.py b/twilio/rest/voice/v1/dialing_permissions/__init__.py index 8e3a4c9b61..2346430adc 100644 --- a/twilio/rest/voice/v1/dialing_permissions/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/__init__.py @@ -1,153 +1,78 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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.rest.voice.v1.dialing_permissions.bulk_country_update import BulkCountryUpdateList +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): - """ 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): + def __init__(self, version: Version): """ Initialize the DialingPermissionsList - :param Version version: Version that contains the resource + :param version: Version that contains the resource - :returns: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList """ - super(DialingPermissionsList, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} + self._uri = "/DialingPermissions" - # Components - self._countries = None - self._settings = None - self._bulk_country_updates = None + self._bulk_country_updates: Optional[BulkCountryUpdateList] = None + self._countries: Optional[CountryList] = None + self._settings: Optional[SettingsList] = None @property - def countries(self): + def bulk_country_updates(self) -> BulkCountryUpdateList: """ - Access the countries + Access the bulk_country_updates + """ + if self._bulk_country_updates is None: + self._bulk_country_updates = BulkCountryUpdateList(self._version) + return self._bulk_country_updates - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList + @property + def countries(self) -> CountryList: + """ + Access the countries """ if self._countries is None: - self._countries = CountryList(self._version, ) + self._countries = CountryList(self._version) return self._countries @property - def settings(self): + def settings(self) -> SettingsList: """ Access the settings - - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList """ if self._settings is None: - self._settings = SettingsList(self._version, ) + self._settings = SettingsList(self._version) return self._settings - @property - def bulk_country_updates(self): - """ - Access the bulk_country_updates - - :returns: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateList - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateList - """ - if self._bulk_country_updates is None: - self._bulk_country_updates = BulkCountryUpdateList(self._version, ) - return self._bulk_country_updates - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DialingPermissionsPage(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 DialingPermissionsPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - - :returns: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsPage - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsPage - """ - super(DialingPermissionsPage, self).__init__(version, response) - - # Path Solution - self._solution = solution - - def get_instance(self, payload): - """ - Build an instance of DialingPermissionsInstance - - :param dict payload: Payload response from the API - - :returns: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsInstance - """ - return DialingPermissionsInstance(self._version, payload, ) - - def __repr__(self): - """ - Provide a friendly representation - - :returns: Machine friendly representation - :rtype: str - """ - return '' - - -class DialingPermissionsInstance(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): - """ - Initialize the DialingPermissionsInstance - - :returns: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsInstance - """ - super(DialingPermissionsInstance, self).__init__(version) - - # Context - self._context = None - 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/voice/v1/dialing_permissions/bulk_country_update.py b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py index bae66f2b98..4059be8dd7 100644 --- a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py +++ b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -1,149 +1,118 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 twilio.base import deserialize -from twilio.base import values +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.page import Page +from twilio.base.version import Version -class BulkCountryUpdateList(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 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): - """ - Initialize the BulkCountryUpdateList + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) - :param Version version: Version that contains the resource + self.update_count: Optional[int] = deserialize.integer( + payload.get("update_count") + ) + self.update_request: Optional[str] = payload.get("update_request") - :returns: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateList - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateList + def __repr__(self) -> str: """ - super(BulkCountryUpdateList, self).__init__(version) - - # Path Solution - self._solution = {} - self._uri = '/DialingPermissions/BulkCountryUpdates'.format(**self._solution) + Provide a friendly representation - def create(self, update_request): + :returns: Machine friendly representation """ - Create the BulkCountryUpdateInstance - - :param unicode update_request: URL encoded JSON array of update objects - :returns: The created BulkCountryUpdateInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance - """ - data = values.of({'UpdateRequest': update_request, }) + return "" - payload = self._version.create(method='POST', uri=self._uri, data=data, ) - return BulkCountryUpdateInstance(self._version, payload, ) +class BulkCountryUpdateList(ListResource): - def __repr__(self): + def __init__(self, version: Version): """ - Provide a friendly representation + Initialize the BulkCountryUpdateList - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param version: Version that contains the resource + """ + super().__init__(version) -class BulkCountryUpdatePage(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. """ + self._uri = "/DialingPermissions/BulkCountryUpdates" - def __init__(self, version, response, solution): + def create(self, update_request: str) -> BulkCountryUpdateInstance: """ - Initialize the BulkCountryUpdatePage + Create the BulkCountryUpdateInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :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: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdatePage - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdatePage + :returns: The created BulkCountryUpdateInstance """ - super(BulkCountryUpdatePage, self).__init__(version, response) - # Path Solution - self._solution = solution + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - def get_instance(self, payload): - """ - Build an instance of BulkCountryUpdateInstance + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param dict payload: Payload response from the API + headers["Accept"] = "application/json" - :returns: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance - """ - return BulkCountryUpdateInstance(self._version, payload, ) + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): - """ - Provide a friendly representation + return BulkCountryUpdateInstance(self._version, payload) - :returns: Machine friendly representation - :rtype: str + async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: """ - return '' + 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\\\" } ]` -class BulkCountryUpdateInstance(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): + :returns: The created BulkCountryUpdateInstance """ - Initialize the BulkCountryUpdateInstance - :returns: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountryUpdateInstance - """ - super(BulkCountryUpdateInstance, self).__init__(version) + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Marshaled Properties - self._properties = { - 'update_count': deserialize.integer(payload.get('update_count')), - 'update_request': payload.get('update_request'), - } + headers["Content-Type"] = "application/x-www-form-urlencoded" - # Context - self._context = None - self._solution = {} + headers["Accept"] = "application/json" - @property - def update_count(self): - """ - :returns: The number of countries updated - :rtype: unicode - """ - return self._properties['update_count'] + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def update_request(self): - """ - :returns: A URL encoded JSON array of update objects - :rtype: unicode - """ - return self._properties['update_request'] + return BulkCountryUpdateInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py index c474e8034d..6a60c23a2f 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -1,448 +1,570 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 -from twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix import HighriskSpecialPrefixList +from twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix import ( + HighriskSpecialPrefixList, +) -class CountryList(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 CountryList +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") - :param Version version: Version that contains the resource + self._solution = { + "iso_code": iso_code or self.iso_code, + } + self._context: Optional[CountryContext] = None - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList - :rtype: twilio.rest.voice.v1.dialing_permissions.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 = '/DialingPermissions/Countries'.format(**self._solution) + :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 stream(self, iso_code=values.unset, continent=values.unset, - country_code=values.unset, low_risk_numbers_enabled=values.unset, - high_risk_special_numbers_enabled=values.unset, - high_risk_tollfraud_numbers_enabled=values.unset, 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 unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code - :param unicode continent: Filter to retrieve the country permissions by specifying the continent - :param unicode country_code: Country code filter - :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled - :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled - :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers 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.voice.v1.dialing_permissions.country.CountryInstance] + :returns: The fetched CountryInstance """ - limits = self._version.read_limits(limit, page_size) + return self._proxy.fetch() - 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'], - ) + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance - return self._version.stream(page, limits['limit']) - def list(self, iso_code=values.unset, continent=values.unset, - country_code=values.unset, low_risk_numbers_enabled=values.unset, - high_risk_special_numbers_enabled=values.unset, - high_risk_tollfraud_numbers_enabled=values.unset, 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 unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code - :param unicode continent: Filter to retrieve the country permissions by specifying the continent - :param unicode country_code: Country code filter - :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled - :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled - :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers 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) + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes + """ + return self._proxy.highrisk_special_prefixes - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.dialing_permissions.country.CountryInstance] + def __repr__(self) -> str: """ - 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, - )) + Provide a friendly representation - def page(self, iso_code=values.unset, continent=values.unset, - country_code=values.unset, low_risk_numbers_enabled=values.unset, - high_risk_special_numbers_enabled=values.unset, - high_risk_tollfraud_numbers_enabled=values.unset, - 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 unicode iso_code: Filter to retrieve the country permissions by specifying the ISO country code - :param unicode continent: Filter to retrieve the country permissions by specifying the continent - :param unicode country_code: Country code filter - :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled - :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled - :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk toll fraud numbers 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 CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage +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 """ - data = values.of({ - 'IsoCode': iso_code, - 'Continent': continent, - 'CountryCode': country_code, - 'LowRiskNumbersEnabled': low_risk_numbers_enabled, - 'HighRiskSpecialNumbersEnabled': high_risk_special_numbers_enabled, - 'HighRiskTollfraudNumbersEnabled': high_risk_tollfraud_numbers_enabled, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + super().__init__(version) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = "/DialingPermissions/Countries/{iso_code}".format(**self._solution) - return CountryPage(self._version, response, self._solution) + self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None - 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.voice.v1.dialing_permissions.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_code): - """ - Constructs a CountryContext + headers["Accept"] = "application/json" - :param iso_code: The ISO country code + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - """ - return CountryContext(self._version, iso_code=iso_code, ) + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) - def __call__(self, iso_code): + async def fetch_async(self) -> CountryInstance: """ - Constructs a CountryContext + Asynchronous coroutine to fetch the CountryInstance - :param iso_code: The ISO country code - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext + :returns: The fetched CountryInstance """ - return CountryContext(self._version, iso_code=iso_code, ) - 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 CountryPage(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 CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) - def __init__(self, version, response, solution): + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes """ - Initialize the CountryPage + if self._highrisk_special_prefixes is None: + self._highrisk_special_prefixes = HighriskSpecialPrefixList( + self._version, + self._solution["iso_code"], + ) + return self._highrisk_special_prefixes - :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.voice.v1.dialing_permissions.country.CountryPage - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryPage + :returns: Machine friendly representation """ - super(CountryPage, 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 CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance - :param dict payload: Payload response from the API - - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance + :param payload: Payload response from the API """ - return CountryInstance(self._version, payload, ) + return CountryInstance(self._version, payload) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" -class CountryContext(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 CountryList(ListResource): - def __init__(self, version, iso_code): + def __init__(self, version: Version): """ - Initialize the CountryContext + Initialize the CountryList - :param Version version: Version that contains the resource - :param iso_code: The ISO country code + :param version: Version that contains the resource - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryContext - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext """ - super(CountryContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {'iso_code': iso_code, } - self._uri = '/DialingPermissions/Countries/{iso_code}'.format(**self._solution) - - # Dependents - self._highrisk_special_prefixes = None + self._uri = "/DialingPermissions/Countries" - def fetch(self): + 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]: """ - Fetch the 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. - :returns: The fetched CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance + :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 """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + 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 CountryInstance(self._version, payload, iso_code=self._solution['iso_code'], ) + 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. - @property - def highrisk_special_prefixes(self): + :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 """ - Access the highrisk_special_prefixes + 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"]) - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList + 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]: """ - if self._highrisk_special_prefixes is None: - self._highrisk_special_prefixes = HighriskSpecialPrefixList( - self._version, - iso_code=self._solution['iso_code'], + 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, ) - return self._highrisk_special_prefixes + ) - def __repr__(self): + 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: """ - 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 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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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"}) -class CountryInstance(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, iso_code=None): - """ - Initialize the CountryInstance - - :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance - """ - super(CountryInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'iso_code': payload.get('iso_code'), - 'name': payload.get('name'), - 'continent': payload.get('continent'), - 'country_codes': payload.get('country_codes'), - 'low_risk_numbers_enabled': payload.get('low_risk_numbers_enabled'), - 'high_risk_special_numbers_enabled': payload.get('high_risk_special_numbers_enabled'), - 'high_risk_tollfraud_numbers_enabled': payload.get('high_risk_tollfraud_numbers_enabled'), - 'url': payload.get('url'), - 'links': payload.get('links'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'iso_code': iso_code or self._properties['iso_code'], } + 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 - @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 + :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: CountryContext for this CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext + :returns: Page of CountryInstance """ - if self._context is None: - self._context = CountryContext(self._version, iso_code=self._solution['iso_code'], ) - return self._context + 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, + } + ) - @property - def iso_code(self): - """ - :returns: The ISO country code - :rtype: unicode - """ - return self._properties['iso_code'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def name(self): - """ - :returns: The name of the country - :rtype: unicode - """ - return self._properties['name'] + headers["Accept"] = "application/json" - @property - def continent(self): - """ - :returns: The name of the continent in which the country is located - :rtype: unicode - """ - return self._properties['continent'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) - @property - def country_codes(self): + def get_page(self, target_url: str) -> CountryPage: """ - :returns: The E.164 assigned country codes(s) - :rtype: unicode - """ - return self._properties['country_codes'] + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def low_risk_numbers_enabled(self): - """ - :returns: Whether dialing to low-risk numbers is enabled - :rtype: bool - """ - return self._properties['low_risk_numbers_enabled'] + :param target_url: API-generated URL for the requested results page - @property - def high_risk_special_numbers_enabled(self): - """ - :returns: Whether dialing to high-risk special services numbers is enabled - :rtype: bool + :returns: Page of CountryInstance """ - return self._properties['high_risk_special_numbers_enabled'] + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) - @property - def high_risk_tollfraud_numbers_enabled(self): + async def get_page_async(self, target_url: str) -> CountryPage: """ - :returns: Whether dialing to high-risk toll fraud numbers is enabled, else `false` - :rtype: bool - """ - return self._properties['high_risk_tollfraud_numbers_enabled'] + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately - @property - def url(self): - """ - :returns: The absolute URL of this resource - :rtype: unicode - """ - return self._properties['url'] + :param target_url: API-generated URL for the requested results page - @property - def links(self): - """ - :returns: A list of URLs related to this resource - :rtype: unicode + :returns: Page of CountryInstance """ - return self._properties['links'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) - def fetch(self): + def get(self, iso_code: str) -> CountryContext: """ - Fetch the CountryInstance + Constructs a CountryContext - :returns: The fetched CountryInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance + :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 self._proxy.fetch() + return CountryContext(self._version, iso_code=iso_code) - @property - def highrisk_special_prefixes(self): + def __call__(self, iso_code: str) -> CountryContext: """ - Access the highrisk_special_prefixes + Constructs a CountryContext - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList + :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 self._proxy.highrisk_special_prefixes + return CountryContext(self._version, iso_code=iso_code) - 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/voice/v1/dialing_permissions/country/highrisk_special_prefix.py b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py index 87df51a272..75300e928c 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py @@ -1,201 +1,290 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ 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, iso_code): + def __init__(self, version: Version, iso_code: str): """ Initialize the HighriskSpecialPrefixList - :param Version version: Version that contains the resource - :param iso_code: The ISO country code + :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 - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList """ - super(HighriskSpecialPrefixList, self).__init__(version) + super().__init__(version) # Path Solution - self._solution = {'iso_code': iso_code, } - self._uri = '/DialingPermissions/Countries/{iso_code}/HighRiskSpecialPrefixes'.format(**self._solution) + self._solution = { + "iso_code": iso_code, + } + self._uri = ( + "/DialingPermissions/Countries/{iso_code}/HighRiskSpecialPrefixes".format( + **self._solution + ) + ) - def stream(self, limit=None, page_size=None): + 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 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance] """ limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + return self._version.stream(page, limits["limit"]) - def list(self, limit=None, page_size=None): + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[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. + 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 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance] """ - return list(self.stream(limit=limit, page_size=page_size, )) + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) - def page(self, page_token=values.unset, page_number=values.unset, - page_size=values.unset): + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: """ - Retrieve a single page of HighriskSpecialPrefixInstance records from the API. - Request is executed immediately + 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 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) - :returns: Page of HighriskSpecialPrefixInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage + :returns: list that will contain up to limit results """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) - response = self._version.page(method='GET', uri=self._uri, params=data, ) + 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. - return HighriskSpecialPrefixPage(self._version, response, self._solution) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 get_page(self, target_url): + :returns: list that will contain up to limit results """ - Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + 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 str target_url: API-generated URL for the requested results page + :param page_token: PageToken provided by the API + :param page_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 - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } ) - return HighriskSpecialPrefixPage(self._version, response, self._solution) - - 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 HighriskSpecialPrefixPage(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 HighriskSpecialPrefixPage - - :param Version version: Version that contains the resource - :param Response response: Response from the API - :param iso_code: The ISO country code + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixPage + async def 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: """ - super(HighriskSpecialPrefixPage, self).__init__(version, response) + Asynchronously retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately - # Path Solution - self._solution = solution + :param page_token: PageToken provided by the 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 get_instance(self, payload): + :returns: Page of HighriskSpecialPrefixInstance """ - Build an instance of HighriskSpecialPrefixInstance + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :param dict payload: Payload response from the API + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance - """ - return HighriskSpecialPrefixInstance(self._version, payload, iso_code=self._solution['iso_code'], ) + headers["Accept"] = "application/json" - def __repr__(self): - """ - Provide a friendly representation + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) - :returns: Machine friendly representation - :rtype: str + def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: """ - return '' - + Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately -class HighriskSpecialPrefixInstance(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 target_url: API-generated URL for the requested results page - def __init__(self, version, payload, iso_code): + :returns: Page of HighriskSpecialPrefixInstance """ - Initialize the HighriskSpecialPrefixInstance + response = self._version.domain.twilio.request("GET", target_url) + return HighriskSpecialPrefixPage(self._version, response, self._solution) - :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixInstance + async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: """ - super(HighriskSpecialPrefixInstance, self).__init__(version) - - # Marshaled Properties - self._properties = {'prefix': payload.get('prefix'), } + Asynchronously retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {'iso_code': iso_code, } + :param target_url: API-generated URL for the requested results page - @property - def prefix(self): - """ - :returns: A prefix that includes the E.164 assigned country code - :rtype: unicode + :returns: Page of HighriskSpecialPrefixInstance """ - return self._properties['prefix'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return HighriskSpecialPrefixPage(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/voice/v1/dialing_permissions/settings.py b/twilio/rest/voice/v1/dialing_permissions/settings.py index 8451ea258e..9e7aa0babb 100644 --- a/twilio/rest/voice/v1/dialing_permissions/settings.py +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -1,242 +1,262 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 twilio.base import values +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 SettingsList(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 SettingsList +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. + """ - :param Version version: Version that contains the resource + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsList - """ - super(SettingsList, self).__init__(version) + self.dialing_permissions_inheritance: Optional[bool] = payload.get( + "dialing_permissions_inheritance" + ) + self.url: Optional[str] = payload.get("url") - # Path Solution - self._solution = {} + self._context: Optional[SettingsContext] = None - def get(self): + @property + def _proxy(self) -> "SettingsContext": """ - Constructs a 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: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + :returns: SettingsContext for this SettingsInstance """ - return SettingsContext(self._version, ) + if self._context is None: + self._context = SettingsContext( + self._version, + ) + return self._context - def __call__(self): + def fetch(self) -> "SettingsInstance": """ - Constructs a SettingsContext + Fetch the SettingsInstance - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - """ - return SettingsContext(self._version, ) - def __repr__(self): + :returns: The fetched SettingsInstance """ - Provide a friendly representation + return self._proxy.fetch() - :returns: Machine friendly representation - :rtype: str + async def fetch_async(self) -> "SettingsInstance": """ - return '' + Asynchronous coroutine to fetch the SettingsInstance -class SettingsPage(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. """ + :returns: The fetched SettingsInstance + """ + return await self._proxy.fetch_async() - def __init__(self, version, response, solution): + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": """ - Initialize the SettingsPage + Update the SettingsInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsPage + :returns: The updated SettingsInstance """ - super(SettingsPage, self).__init__(version, response) + return self._proxy.update( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) - # Path Solution - self._solution = solution - - def get_instance(self, payload): + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": """ - Build an instance of SettingsInstance + Asynchronous coroutine to update the SettingsInstance - :param dict payload: Payload response from the API + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance + :returns: The updated SettingsInstance """ - return SettingsInstance(self._version, payload, ) + return await self._proxy.update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + + return "" class SettingsContext(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): + def __init__(self, version: Version): """ Initialize the SettingsContext - :param Version version: Version that contains the resource - - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext + :param version: Version that contains the resource """ - super(SettingsContext, self).__init__(version) + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/Settings'.format(**self._solution) + self._uri = "/Settings" - def fetch(self): + def fetch(self) -> SettingsInstance: """ Fetch the SettingsInstance + :returns: The fetched SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return SettingsInstance(self._version, payload, ) + headers = values.of({}) - def update(self, dialing_permissions_inheritance=values.unset): + 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: """ - Update the SettingsInstance + Asynchronous coroutine to fetch the SettingsInstance - :param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false` - :returns: The updated SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance + :returns: The fetched SettingsInstance """ - data = values.of({'DialingPermissionsInheritance': dialing_permissions_inheritance, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + headers = values.of({}) + + headers["Accept"] = "application/json" - return SettingsInstance(self._version, payload, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - def __repr__(self): + return SettingsInstance( + self._version, + payload, + ) + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: """ - Provide a friendly representation + Update the SettingsInstance - :returns: Machine friendly representation - :rtype: str + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) -class SettingsInstance(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["Content-Type"] = "application/x-www-form-urlencoded" - def __init__(self, version, payload): + 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: """ - Initialize the SettingsInstance + Asynchronous coroutine to update the SettingsInstance - :returns: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.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 """ - super(SettingsInstance, self).__init__(version) - # Marshaled Properties - self._properties = { - 'dialing_permissions_inheritance': payload.get('dialing_permissions_inheritance'), - 'url': payload.get('url'), - } + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) - # Context - self._context = None - self._solution = {} + 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: SettingsContext for this SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsContext - """ - if self._context is None: - self._context = SettingsContext(self._version, ) - return self._context + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def dialing_permissions_inheritance(self): - """ - :returns: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false` - :rtype: bool + return SettingsInstance(self._version, payload) + + def __repr__(self) -> str: """ - return self._properties['dialing_permissions_inheritance'] + Provide a friendly representation - @property - def url(self): + :returns: Machine friendly representation """ - :returns: The absolute URL of this resource - :rtype: unicode + + return "" + + +class SettingsList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['url'] + Initialize the SettingsList + + :param version: Version that contains the resource - def fetch(self): """ - Fetch the SettingsInstance + super().__init__(version) - :returns: The fetched SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance + def get(self) -> SettingsContext: """ - return self._proxy.fetch() + Constructs a SettingsContext - def update(self, dialing_permissions_inheritance=values.unset): """ - Update the SettingsInstance + return SettingsContext(self._version) - :param bool dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false` + def __call__(self) -> SettingsContext: + """ + Constructs a SettingsContext - :returns: The updated SettingsInstance - :rtype: twilio.rest.voice.v1.dialing_permissions.settings.SettingsInstance """ - return self._proxy.update(dialing_permissions_inheritance=dialing_permissions_inheritance, ) + return SettingsContext(self._version) - 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/voice/v1/ip_record.py b/twilio/rest/voice/v1/ip_record.py index e933a6e214..05e9741fa5 100644 --- a/twilio/rest/voice/v1/ip_record.py +++ b/twilio/rest/voice/v1/ip_record.py @@ -1,412 +1,619 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 IpRecordList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the IpRecordList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[IpRecordContext] = None - :returns: twilio.rest.voice.v1.ip_record.IpRecordList - :rtype: twilio.rest.voice.v1.ip_record.IpRecordList + @property + def _proxy(self) -> "IpRecordContext": """ - super(IpRecordList, 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 = '/IpRecords'.format(**self._solution) + :returns: IpRecordContext for this IpRecordInstance + """ + if self._context is None: + self._context = IpRecordContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, ip_address, friendly_name=values.unset, - cidr_prefix_length=values.unset): + def delete(self) -> bool: """ - Create the IpRecordInstance + Deletes the IpRecordInstance - :param unicode ip_address: An IP address in dotted decimal notation, IPv4 only. - :param unicode friendly_name: A string to describe the resource - :param unicode 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 - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({ - 'IpAddress': ip_address, - 'FriendlyName': friendly_name, - 'CidrPrefixLength': cidr_prefix_length, - }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance - return IpRecordInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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 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.voice.v1.ip_record.IpRecordInstance] + def fetch(self) -> "IpRecordInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the IpRecordInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched IpRecordInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the IpRecordInstance - :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.voice.v1.ip_record.IpRecordInstance] + :returns: The fetched IpRecordInstance """ - 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, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": """ - Retrieve a single page of IpRecordInstance records from the API. - Request is executed immediately + Update the IpRecordInstance - :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 is not unique and can be up to 255 characters long. - :returns: Page of IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordPage + :returns: The updated IpRecordInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return IpRecordPage(self._version, response, self._solution) + return self._proxy.update( + friendly_name=friendly_name, + ) - def get_page(self, target_url): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": """ - Retrieve a specific page of IpRecordInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the IpRecordInstance - :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 is not unique and can be up to 255 characters long. - :returns: Page of IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordPage + :returns: The updated IpRecordInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + friendly_name=friendly_name, ) - return IpRecordPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a IpRecordContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.ip_record.IpRecordContext - :rtype: twilio.rest.voice.v1.ip_record.IpRecordContext +class IpRecordContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return IpRecordContext(self._version, sid=sid, ) + Initialize the IpRecordContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. """ - Constructs a IpRecordContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpRecords/{sid}".format(**self._solution) - :returns: twilio.rest.voice.v1.ip_record.IpRecordContext - :rtype: twilio.rest.voice.v1.ip_record.IpRecordContext + def delete(self) -> bool: """ - return IpRecordContext(self._version, sid=sid, ) + Deletes the IpRecordInstance - 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 IpRecordPage(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 IpRecordPage + Asynchronous coroutine that deletes the IpRecordInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.voice.v1.ip_record.IpRecordPage - :rtype: twilio.rest.voice.v1.ip_record.IpRecordPage + :returns: True if delete succeeds, False otherwise """ - super(IpRecordPage, 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) -> IpRecordInstance: """ - Build an instance of IpRecordInstance + Fetch the IpRecordInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.voice.v1.ip_record.IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance + :returns: The fetched IpRecordInstance """ - return IpRecordInstance(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 IpRecordContext(InstanceContext): - """ """ + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> IpRecordInstance: """ - Initialize the IpRecordContext + Asynchronous coroutine to fetch the IpRecordInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.ip_record.IpRecordContext - :rtype: twilio.rest.voice.v1.ip_record.IpRecordContext + :returns: The fetched IpRecordInstance """ - super(IpRecordContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/IpRecords/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): - """ - Fetch the IpRecordInstance + headers["Accept"] = "application/json" - :returns: The fetched IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance - """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - return IpRecordInstance(self._version, payload, sid=self._solution['sid'], ) + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, friendly_name=values.unset): + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: """ Update the IpRecordInstance - :param unicode friendly_name: A string to describe the resource + :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 - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance """ - data = values.of({'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + 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'], ) + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) - def delete(self): + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: """ - Deletes the IpRecordInstance + Asynchronous coroutine to update the IpRecordInstance - :returns: True if delete succeeds, False otherwise - :rtype: bool + :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._version.delete(method='DELETE', uri=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 IpRecordInstance(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 IpRecordInstance(InstanceResource): - """ """ +class IpRecordPage(Page): - def __init__(self, version, payload, sid=None): + def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: """ - Initialize the IpRecordInstance + Build an instance of IpRecordInstance - :returns: twilio.rest.voice.v1.ip_record.IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance + :param payload: Payload response from the API """ - super(IpRecordInstance, self).__init__(version) + return IpRecordInstance(self._version, payload) - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'sid': payload.get('sid'), - 'friendly_name': payload.get('friendly_name'), - 'ip_address': payload.get('ip_address'), - 'cidr_prefix_length': deserialize.integer(payload.get('cidr_prefix_length')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + def __repr__(self) -> str: + """ + Provide a friendly representation - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + :returns: Machine friendly representation + """ + return "" - @property - def _proxy(self): + +class IpRecordList(ListResource): + + 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 IpRecordList + + :param version: Version that contains the resource - :returns: IpRecordContext for this IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordContext """ - if self._context is None: - self._context = IpRecordContext(self._version, sid=self._solution['sid'], ) - return self._context + super().__init__(version) - @property - def account_sid(self): + 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: """ - :returns: The SID of the Account that created the resource - :rtype: unicode + 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 """ - return self._properties['account_sid'] - @property - def sid(self): + 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: """ - :returns: The unique string that identifies the resource - :rtype: unicode + 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 """ - return self._properties['sid'] - @property - def friendly_name(self): + 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]: """ - :returns: The string that you assigned to describe the resource - :rtype: unicode + 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 """ - return self._properties['friendly_name'] + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) - @property - def ip_address(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpRecordInstance]: """ - :returns: An IP address in dotted decimal notation, IPv4 only. - :rtype: unicode + 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 """ - return self._properties['ip_address'] + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) - @property - def cidr_prefix_length(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: """ - :returns: 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. - :rtype: unicode + 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 self._properties['cidr_prefix_length'] + 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[IpRecordInstance]: """ - :returns: The RFC 2822 date and time in GMT that the resource was created - :rtype: datetime + 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: """ - return self._properties['date_created'] + Retrieve a single page of IpRecordInstance 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 IpRecordInstance """ - :returns: The RFC 2822 date and time in GMT that the resource was last 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 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: """ - return self._properties['date_updated'] + Asynchronously retrieve a single page of IpRecordInstance 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 IpRecordInstance """ - :returns: The absolute URL of the 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 IpRecordPage(self._version, response) + + def get_page(self, target_url: str) -> IpRecordPage: """ - return self._properties['url'] + Retrieve a specific page of IpRecordInstance 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 IpRecordInstance """ - Fetch the IpRecordInstance + response = self._version.domain.twilio.request("GET", target_url) + return IpRecordPage(self._version, response) - :returns: The fetched IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance + async def get_page_async(self, target_url: str) -> IpRecordPage: """ - return self._proxy.fetch() + 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 - def update(self, friendly_name=values.unset): + :returns: Page of IpRecordInstance """ - Update the IpRecordInstance + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpRecordPage(self._version, response) - :param unicode friendly_name: A string to describe the resource + def get(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext - :returns: The updated IpRecordInstance - :rtype: twilio.rest.voice.v1.ip_record.IpRecordInstance + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. """ - return self._proxy.update(friendly_name=friendly_name, ) + return IpRecordContext(self._version, sid=sid) - def delete(self): + def __call__(self, sid: str) -> IpRecordContext: """ - Deletes the IpRecordInstance + Constructs a IpRecordContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. """ - return self._proxy.delete() + return IpRecordContext(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/voice/v1/source_ip_mapping.py b/twilio/rest/voice/v1/source_ip_mapping.py index e4bcd59e66..749d2b0034 100644 --- a/twilio/rest/voice/v1/source_ip_mapping.py +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -1,388 +1,599 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 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 SourceIpMappingList(ListResource): - """ """ - - def __init__(self, version): - """ - Initialize the SourceIpMappingList +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") - :param Version version: Version that contains the resource + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SourceIpMappingContext] = None - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingList - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingList + @property + def _proxy(self) -> "SourceIpMappingContext": """ - super(SourceIpMappingList, 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 = '/SourceIpMappings'.format(**self._solution) + :returns: SourceIpMappingContext for this SourceIpMappingInstance + """ + if self._context is None: + self._context = SourceIpMappingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def create(self, ip_record_sid, sip_domain_sid): + def delete(self) -> bool: """ - Create the SourceIpMappingInstance + Deletes the SourceIpMappingInstance - :param unicode ip_record_sid: The unique string that identifies an IP Record - :param unicode sip_domain_sid: The unique string that identifies a SIP Domain - :returns: The created SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance + :returns: True if delete succeeds, False otherwise """ - data = values.of({'IpRecordSid': ip_record_sid, 'SipDomainSid': sip_domain_sid, }) + return self._proxy.delete() - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance - return SourceIpMappingInstance(self._version, payload, ) - def stream(self, limit=None, page_size=None): + :returns: True if delete succeeds, False otherwise """ - 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. + 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.voice.v1.source_ip_mapping.SourceIpMappingInstance] + def fetch(self) -> "SourceIpMappingInstance": """ - limits = self._version.read_limits(limit, page_size) + Fetch the SourceIpMappingInstance - page = self.page(page_size=limits['page_size'], ) - return self._version.stream(page, limits['limit']) + :returns: The fetched SourceIpMappingInstance + """ + return self._proxy.fetch() - def list(self, limit=None, page_size=None): + async def fetch_async(self) -> "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. + Asynchronous coroutine to fetch the SourceIpMappingInstance - :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.voice.v1.source_ip_mapping.SourceIpMappingInstance] + :returns: The fetched SourceIpMappingInstance """ - 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, sip_domain_sid: str) -> "SourceIpMappingInstance": """ - Retrieve a single page of SourceIpMappingInstance records from the API. - Request is executed immediately + Update the SourceIpMappingInstance - :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 sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - :returns: Page of SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingPage + :returns: The updated SourceIpMappingInstance """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return SourceIpMappingPage(self._version, response, self._solution) + return self._proxy.update( + sip_domain_sid=sip_domain_sid, + ) - def get_page(self, target_url): + async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": """ - Retrieve a specific page of SourceIpMappingInstance records from the API. - Request is executed immediately + Asynchronous coroutine to update the SourceIpMappingInstance - :param str target_url: API-generated URL for the requested results page + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - :returns: Page of SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingPage + :returns: The updated SourceIpMappingInstance """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + return await self._proxy.update_async( + sip_domain_sid=sip_domain_sid, ) - return SourceIpMappingPage(self._version, response, self._solution) + def __repr__(self) -> str: + """ + Provide a friendly representation - def get(self, sid): + :returns: Machine friendly representation """ - Constructs a SourceIpMappingContext + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext +class SourceIpMappingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - return SourceIpMappingContext(self._version, sid=sid, ) + Initialize the SourceIpMappingContext - def __call__(self, sid): + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. """ - Constructs a SourceIpMappingContext + super().__init__(version) - :param sid: The unique string that identifies the resource + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SourceIpMappings/{sid}".format(**self._solution) - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext + def delete(self) -> bool: """ - return SourceIpMappingContext(self._version, sid=sid, ) + Deletes the SourceIpMappingInstance - 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 SourceIpMappingPage(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 SourceIpMappingPage + Asynchronous coroutine that deletes the SourceIpMappingInstance - :param Version version: Version that contains the resource - :param Response response: Response from the API - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingPage - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingPage + :returns: True if delete succeeds, False otherwise """ - super(SourceIpMappingPage, 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) -> SourceIpMappingInstance: """ - Build an instance of SourceIpMappingInstance + Fetch the SourceIpMappingInstance - :param dict payload: Payload response from the API - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance + :returns: The fetched SourceIpMappingInstance """ - return SourceIpMappingInstance(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 SourceIpMappingContext(InstanceContext): - """ """ + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def __init__(self, version, sid): + async def fetch_async(self) -> SourceIpMappingInstance: """ - Initialize the SourceIpMappingContext + Asynchronous coroutine to fetch the SourceIpMappingInstance - :param Version version: Version that contains the resource - :param sid: The unique string that identifies the resource - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext + :returns: The fetched SourceIpMappingInstance """ - super(SourceIpMappingContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/SourceIpMappings/{sid}'.format(**self._solution) + headers = values.of({}) - def fetch(self): + 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: """ - Fetch the SourceIpMappingInstance + Update the SourceIpMappingInstance - :returns: The fetched SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return SourceIpMappingInstance(self._version, payload, sid=self._solution['sid'], ) + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) - def update(self, sip_domain_sid): + headers["Content-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: """ - Update the SourceIpMappingInstance + Asynchronous coroutine to update the SourceIpMappingInstance - :param unicode sip_domain_sid: The unique string that identifies a SIP Domain + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. :returns: The updated SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance """ - data = values.of({'SipDomainSid': sip_domain_sid, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SourceIpMappingInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Accept"] = "application/json" - def delete(self): + 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: """ - Deletes the SourceIpMappingInstance + 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 SourceIpMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: + """ + Build an instance of SourceIpMappingInstance + + :param payload: Payload response from the API """ - return self._version.delete(method='DELETE', uri=self._uri, ) + return SourceIpMappingInstance(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 SourceIpMappingInstance(InstanceResource): - """ """ +class SourceIpMappingList(ListResource): - def __init__(self, version, payload, sid=None): + def __init__(self, version: Version): """ - Initialize the SourceIpMappingInstance + Initialize the SourceIpMappingList + + :param version: Version that contains the resource - :returns: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance """ - super(SourceIpMappingInstance, self).__init__(version) + super().__init__(version) - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'ip_record_sid': payload.get('ip_record_sid'), - 'sip_domain_sid': payload.get('sip_domain_sid'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + self._uri = "/SourceIpMappings" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + def create( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Create the SourceIpMappingInstance - @property - def _proxy(self): + :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 """ - 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 - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingContext + 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: """ - if self._context is None: - self._context = SourceIpMappingContext(self._version, sid=self._solution['sid'], ) - return self._context + Asynchronously create the SourceIpMappingInstance - @property - def sid(self): + :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 """ - :returns: The unique string that identifies the resource - :rtype: unicode + + 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]: """ - return self._properties['sid'] + 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. - @property - def ip_record_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 unique string that identifies an IP Record - :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[SourceIpMappingInstance]: """ - return self._properties['ip_record_sid'] + 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. - @property - def sip_domain_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 unique string that identifies a SIP Domain - :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[SourceIpMappingInstance]: """ - return self._properties['sip_domain_sid'] + Lists SourceIpMappingInstance 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 RFC 2822 date and time in GMT that the 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[SourceIpMappingInstance]: """ - return self._properties['date_created'] + 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. - @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, + ) -> SourceIpMappingPage: """ - :returns: The RFC 2822 date and time in GMT that the resource was last updated - :rtype: datetime + 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 """ - 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 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: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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 """ - 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) - def fetch(self): + def get_page(self, target_url: str) -> SourceIpMappingPage: """ - Fetch the SourceIpMappingInstance + Retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately - :returns: The fetched SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance """ - return self._proxy.fetch() + response = self._version.domain.twilio.request("GET", target_url) + return SourceIpMappingPage(self._version, response) - def update(self, sip_domain_sid): + async def get_page_async(self, target_url: str) -> SourceIpMappingPage: """ - Update the SourceIpMappingInstance + Asynchronously retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately - :param unicode sip_domain_sid: The unique string that identifies a SIP Domain + :param target_url: API-generated URL for the requested results page - :returns: The updated SourceIpMappingInstance - :rtype: twilio.rest.voice.v1.source_ip_mapping.SourceIpMappingInstance + :returns: Page of SourceIpMappingInstance """ - return self._proxy.update(sip_domain_sid, ) + response = await self._version.domain.twilio.request_async("GET", target_url) + return SourceIpMappingPage(self._version, response) - def delete(self): + def get(self, sid: str) -> SourceIpMappingContext: """ - Deletes the SourceIpMappingInstance + Constructs a SourceIpMappingContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. """ - return self._proxy.delete() + 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): + 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/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 df3e45da84..3b7a40977c 100644 --- a/twilio/rest/wireless/__init__.py +++ b/twilio/rest/wireless/__init__.py @@ -1,74 +1,43 @@ -# coding=utf-8 -r""" -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 - - @property - def usage_records(self): - """ - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordList - """ + 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 c0b2cbdcdf..8f4d0dc5d7 100644 --- a/twilio/rest/wireless/v1/__init__.py +++ b/twilio/rest/wireless/v1/__init__.py @@ -1,12 +1,20 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 @@ -15,61 +23,45 @@ 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._usage_records = None - 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 usage_records(self): - """ - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordList - """ - if self._usage_records is None: - self._usage_records = UsageRecordList(self) - return self._usage_records - - @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 f03d1e3050..a6e8f0b39d 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -1,486 +1,669 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +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" - def stream(self, sim=values.unset, status=values.unset, direction=values.unset, - transport=values.unset, limit=None, page_size=None): - """ - 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. + """ + :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") - :param unicode sim: The sid or unique_name of the Sim resources to read - :param CommandInstance.Status status: The status of the resources to read - :param CommandInstance.Direction direction: Only return Commands with this direction value - :param CommandInstance.Transport transport: Only return Commands with this transport value - :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) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.command.CommandInstance] + @property + def _proxy(self) -> "CommandContext": """ - limits = self._version.read_limits(limit, page_size) - - page = self.page( - sim=sim, - status=status, - direction=direction, - transport=transport, - page_size=limits['page_size'], - ) + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - return self._version.stream(page, limits['limit']) + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, sim=values.unset, status=values.unset, direction=values.unset, - transport=values.unset, limit=None, page_size=None): + def delete(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. + Deletes the CommandInstance - :param unicode sim: The sid or unique_name of the Sim resources to read - :param CommandInstance.Status status: The status of the resources to read - :param CommandInstance.Direction direction: Only return Commands with this direction value - :param CommandInstance.Transport transport: Only return Commands with this transport value - :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, - transport=transport, - limit=limit, - page_size=page_size, - )) + return self._proxy.delete() - def page(self, sim=values.unset, status=values.unset, direction=values.unset, - transport=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 CommandInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes the CommandInstance - :param unicode sim: The sid or unique_name of the Sim resources to read - :param CommandInstance.Status status: The status of the resources to read - :param CommandInstance.Direction direction: Only return Commands with this direction value - :param CommandInstance.Transport transport: Only return Commands with this transport value - :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: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CommandInstance": """ - data = values.of({ - 'Sim': sim, - 'Status': status, - 'Direction': direction, - 'Transport': transport, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + Fetch the CommandInstance - response = self._version.page(method='GET', uri=self._uri, params=data, ) - return CommandPage(self._version, response, self._solution) + :returns: The fetched CommandInstance + """ + 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, delivery_receipt_requested=values.unset): + :returns: Machine friendly representation """ - Create the CommandInstance + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param unicode command: The message body of the Command or a Base64 encoded byte string in binary mode - :param unicode sim: The sid or unique_name of the SIM to send the Command to - :param unicode callback_method: The HTTP method we use to call callback_url - :param unicode callback_url: he URL we call when the Command has finished sending - :param CommandInstance.CommandMode command_mode: The mode to use when sending the SMS message - :param unicode include_sid: Whether to include the SID of the command in the message body - :param bool delivery_receipt_requested: Whether to request delivery receipt from the recipient - :returns: The created CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance +class CommandContext(InstanceContext): + + 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, - 'DeliveryReceiptRequested': delivery_receipt_requested, - }) + Initialize the CommandContext - payload = self._version.create(method='POST', uri=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 that identifies the resource to fetch - :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 that identifies the resource to fetch + 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): - """ """ + 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): - """ """ +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 that identifies the resource to fetch + 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 fetch(self): + def __repr__(self) -> str: """ - Fetch the CommandInstance + Provide a friendly representation - :returns: The fetched CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance + :returns: Machine friendly representation """ - payload = self._version.fetch(method='GET', uri=self._uri, ) + return "" - return CommandInstance(self._version, payload, sid=self._solution['sid'], ) - def delete(self): +class CommandList(ListResource): + + def __init__(self, version: Version): """ - Deletes the CommandInstance + Initialize the CommandList + + :param version: Version that contains the resource - :returns: True if delete succeeds, False otherwise - :rtype: bool """ - return self._version.delete(method='DELETE', uri=self._uri, ) + super().__init__(version) - def __repr__(self): + 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: """ - Provide a friendly representation + Create the CommandInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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): - """ """ + 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 = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) - class CommandMode(object): - TEXT = "text" - BINARY = "binary" + 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`. - class Transport(object): - SMS = "sms" - IP = "ip" + :returns: The created CommandInstance + """ - def __init__(self, version, payload, sid=None): - """ - Initialize the CommandInstance - - :returns: twilio.rest.wireless.v1.command.CommandInstance - :rtype: twilio.rest.wireless.v1.command.CommandInstance - """ - super(CommandInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sid': payload.get('sid'), - 'account_sid': payload.get('account_sid'), - 'sim_sid': payload.get('sim_sid'), - 'command': payload.get('command'), - 'command_mode': payload.get('command_mode'), - 'transport': payload.get('transport'), - 'delivery_receipt_requested': payload.get('delivery_receipt_requested'), - 'status': payload.get('status'), - 'direction': payload.get('direction'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + 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"}) - # 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: 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 + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] + return CommandInstance(self._version, payload) - @property - def account_sid(self): + 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]: """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_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 sim_sid(self): - """ - :returns: The SID of the Sim resource that the Command was sent to or from - :rtype: unicode - """ - return self._properties['sim_sid'] + :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 command(self): - """ - :returns: The message being sent to or from the SIM - :rtype: unicode + :returns: Generator that will yield up to limit results """ - return self._properties['command'] + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) - @property - def command_mode(self): - """ - :returns: The mode used to send the SMS message - :rtype: CommandInstance.CommandMode - """ - return self._properties['command_mode'] + return self._version.stream(page, limits["limit"]) - @property - def transport(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]: """ - :returns: The type of transport used - :rtype: CommandInstance.Transport - """ - return self._properties['transport'] + 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 delivery_receipt_requested(self): - """ - :returns: Whether to request a delivery receipt - :rtype: bool - """ - return self._properties['delivery_receipt_requested'] + :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 status(self): - """ - :returns: The status of the Command - :rtype: CommandInstance.Status + :returns: Generator that will yield up to limit results """ - return self._properties['status'] + 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 direction(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: """ - :returns: The direction of the Command - :rtype: CommandInstance.Direction + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: """ - return self._properties['direction'] + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately - @property - def date_created(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 ISO 8601 date and time in GMT when the resource was created - :rtype: datetime + 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['date_created'] + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "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 CommandPage(self._version, response) + + def get_page(self, target_url: str) -> CommandPage: """ - :returns: The ISO 8601 date and time in GMT when the resource was last updated format - :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_updated'] + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) - @property - def url(self): + async def get_page_async(self, target_url: str) -> CommandPage: """ - :returns: The absolute URL of the resource - :rtype: unicode + 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['url'] + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) - def fetch(self): + def get(self, sid: str) -> CommandContext: """ - Fetch the CommandInstance + Constructs a CommandContext - :returns: The 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 delete(self): + def __call__(self, sid: str) -> CommandContext: """ - Deletes the CommandInstance + Constructs a CommandContext - :returns: True if delete succeeds, False otherwise - :rtype: bool + :param sid: The SID of the Command resource to fetch. """ - return self._proxy.delete() + 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 f194443528..23efabe9b0 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -1,512 +1,728 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version): - """ - Initialize the RatePlanList +class RatePlanInstance(InstanceResource): - :param Version version: Version that contains the resource + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" - :returns: twilio.rest.wireless.v1.rate_plan.RatePlanList - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanList - """ - super(RatePlanList, self).__init__(version) + """ + :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") - # Path Solution - self._solution = {} - self._uri = '/RatePlans'.format(**self._solution) + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None - def stream(self, limit=None, page_size=None): + @property + def _proxy(self) -> "RatePlanContext": """ - 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) + 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.rate_plan.RatePlanInstance] + :returns: RatePlanContext for this RatePlanInstance """ - limits = self._version.read_limits(limit, page_size) - - page = self.page(page_size=limits['page_size'], ) - - return self._version.stream(page, limits['limit']) + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - def list(self, limit=None, page_size=None): + def delete(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. + 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 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 RatePlanInstance records from the API. - Request is executed immediately + Asynchronous coroutine that deletes 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: True if delete succeeds, False otherwise """ - data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) - - return RatePlanPage(self._version, response, self._solution) + return await self._proxy.delete_async() - def get_page(self, target_url): + def fetch(self) -> "RatePlanInstance": """ - Retrieve a specific page of RatePlanInstance records from the API. - Request is executed immediately + 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) + return self._proxy.fetch() - 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): + async def fetch_async(self) -> "RatePlanInstance": """ - Create the RatePlanInstance + Asynchronous coroutine to fetch the RatePlanInstance - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode friendly_name: A string to describe the resource - :param bool data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity - :param unicode data_limit: The total data usage in Megabytes that the Network allows during one month on the home network - :param unicode data_metering: The model used to meter data usage - :param bool messaging_enabled: Whether SIMs can make, send, and receive SMS using Commands - :param bool voice_enabled: Whether SIMs can make and receive voice calls - :param bool national_roaming_enabled: Whether SIMs can roam on networks other than the home network in the United States - :param unicode international_roaming: The services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States - :param unicode national_roaming_data_limit: The total data usage in Megabytes that the Network allows during one month on non-home networks in the United States - :param unicode 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 - :returns: The created RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance + :returns: The fetched 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, - }) - - payload = self._version.create(method='POST', uri=self._uri, data=data, ) + return await self._proxy.fetch_async() - 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 that identifies the resource to fetch + :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 that identifies the resource to fetch + :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): - """ """ +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): - """ """ + 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 that identifies the resource to fetch - :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({}) + + 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 the RatePlanInstance + Asynchronous coroutine to fetch the RatePlanInstance + :returns: The fetched RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - def update(self, unique_name=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: An application-defined string that uniquely identifies the resource - :param unicode friendly_name: A string to describe the resource + :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 - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanInstance """ - data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, }) - payload = self._version.update(method='POST', uri=self._uri, data=data, ) + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) - return RatePlanInstance(self._version, payload, sid=self._solution['sid'], ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def delete(self): - """ - Deletes the RatePlanInstance + headers["Accept"] = "application/json" - :returns: True if delete succeeds, False otherwise - :rtype: bool - """ - return self._version.delete(method='DELETE', uri=self._uri, ) + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self): + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: """ - Provide a friendly representation + Asynchronous coroutine to update the RatePlanInstance - :returns: Machine friendly representation - :rtype: str + :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 """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) -class RatePlanInstance(InstanceResource): - """ """ + headers["Content-Type"] = "application/x-www-form-urlencoded" - class DataLimitStrategy(object): - BLOCK = "block" - THROTTLE = "throttle" + headers["Accept"] = "application/json" - 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'friendly_name': payload.get('friendly_name'), - 'data_enabled': payload.get('data_enabled'), - 'data_metering': payload.get('data_metering'), - 'data_limit': deserialize.integer(payload.get('data_limit')), - 'messaging_enabled': payload.get('messaging_enabled'), - 'voice_enabled': payload.get('voice_enabled'), - 'national_roaming_enabled': payload.get('national_roaming_enabled'), - 'national_roaming_data_limit': deserialize.integer(payload.get('national_roaming_data_limit')), - 'international_roaming': payload.get('international_roaming'), - 'international_roaming_data_limit': deserialize.integer(payload.get('international_roaming_data_limit')), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - } + 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 RatePlanInstance(self._version, payload, sid=self._solution["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: RatePlanContext for this RatePlanInstance - :rtype: twilio.rest.wireless.v1.rate_plan.RatePlanContext + :returns: Machine friendly representation """ - if self._context is None: - self._context = RatePlanContext(self._version, sid=self._solution['sid'], ) - return self._context + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def sid(self): - """ - :returns: The unique string that identifies the resource - :rtype: unicode - """ - return self._properties['sid'] - @property - def unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] +class RatePlanPage(Page): - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ - return self._properties['account_sid'] + Build an instance of RatePlanInstance - @property - def friendly_name(self): + :param payload: Payload response from the API """ - :returns: The string that you assigned to describe the resource - :rtype: unicode - """ - return self._properties['friendly_name'] + return RatePlanInstance(self._version, payload) - @property - def data_enabled(self): - """ - :returns: Whether SIMs can use GPRS/3G/4G/LTE data connectivity - :rtype: bool + def __repr__(self) -> str: """ - return self._properties['data_enabled'] + Provide a friendly representation - @property - def data_metering(self): - """ - :returns: The model used to meter data usage - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['data_metering'] + return "" - @property - def data_limit(self): - """ - :returns: The total data usage in Megabytes that the Network allows during one month on the home network - :rtype: unicode - """ - return self._properties['data_limit'] - @property - def messaging_enabled(self): - """ - :returns: Whether SIMs can make, send, and receive SMS using Commands - :rtype: bool +class RatePlanList(ListResource): + + def __init__(self, version: Version): """ - return self._properties['messaging_enabled'] + Initialize the RatePlanList + + :param version: Version that contains the resource - @property - def voice_enabled(self): """ - :returns: Whether SIMs can make and receive voice calls - :rtype: bool + 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: """ - return self._properties['voice_enabled'] + Create the RatePlanInstance - @property - def national_roaming_enabled(self): + :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 """ - :returns: Whether SIMs can roam on networks other than the home network in the United States - :rtype: bool + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance """ - return self._properties['national_roaming_enabled'] - @property - def national_roaming_data_limit(self): + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: """ - :returns: The total data usage in Megabytes that the Network allows during one month on non-home networks in the United States - :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 services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States - :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 total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States - :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 when the resource was created, given as GMT in ISO 8601 format - :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 when the resource was last updated, given as GMT in ISO 8601 format - :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 absolute URL of the 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 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 + + :param target_url: API-generated URL for the requested results page - def fetch(self): + :returns: Page of RatePlanInstance """ - Fetch the RatePlanInstance + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) - :returns: The 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 + + :param target_url: API-generated URL for the requested results page - def update(self, unique_name=values.unset, friendly_name=values.unset): + :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: An application-defined string that uniquely identifies the resource - :param unicode friendly_name: A string to describe the resource + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext - :returns: The 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 f5b6ea0926..cba0eeec71 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -1,732 +1,942 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ +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. + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context - :param SimInstance.Status status: Only return Sim resources with this status - :param unicode iccid: Only return Sim resources with this ICCID - :param unicode rate_plan: Only return Sim resources assigned to this RatePlan resource - :param unicode e_id: Deprecated - :param unicode sim_registration_code: Only return Sim resources with this 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: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.sim.SimInstance] + def delete(self) -> bool: """ - limits = self._version.read_limits(limit, page_size) + Deletes the SimInstance - 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']) + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() - 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): + async def delete_async(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. + Asynchronous coroutine that deletes the SimInstance - :param SimInstance.Status status: Only return Sim resources with this status - :param unicode iccid: Only return Sim resources with this ICCID - :param unicode rate_plan: Only return Sim resources assigned to this RatePlan resource - :param unicode e_id: Deprecated - :param unicode sim_registration_code: Only return Sim resources with this 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 await self._proxy.delete_async() - 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 + Fetch the SimInstance - :param SimInstance.Status status: Only return Sim resources with this status - :param unicode iccid: Only return Sim resources with this ICCID - :param unicode rate_plan: Only return Sim resources assigned to this RatePlan resource - :param unicode e_id: Deprecated - :param unicode sim_registration_code: Only return Sim resources with this 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 + :returns: The fetched SimInstance """ - data = values.of({ - 'Status': status, - 'Iccid': iccid, - 'RatePlan': rate_plan, - 'EId': e_id, - 'SimRegistrationCode': sim_registration_code, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) + return self._proxy.fetch() - response = self._version.page(method='GET', uri=self._uri, params=data, ) + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to 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 await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance - :param str target_url: API-generated URL for the requested results page + :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: Page of SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimPage + :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). - def get(self, sid): + :returns: The updated SimInstance """ - Constructs a SimContext - - :param sid: The SID of the Sim resource to fetch + 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, + ) - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + @property + def data_sessions(self) -> DataSessionList: """ - return SimContext(self._version, sid=sid, ) - - def __call__(self, sid): + Access the data_sessions """ - Constructs a SimContext - - :param sid: The SID of the Sim resource to fetch + return self._proxy.data_sessions - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + @property + def usage_records(self) -> UsageRecordList: """ - return SimContext(self._version, sid=sid, ) + Access the usage_records + """ + 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): - """ """ +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 - - 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._data_sessions: Optional[DataSessionList] = None + self._usage_records: Optional[UsageRecordList] = None - :returns: twilio.rest.wireless.v1.sim.SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + def delete(self) -> bool: """ - return SimInstance(self._version, payload, ) + Deletes the SimInstance - 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 SimContext(InstanceContext): - """ """ + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - def __init__(self, version, sid): + async def delete_async(self) -> bool: """ - Initialize the SimContext + Asynchronous coroutine that deletes the SimInstance - :param Version version: Version that contains the resource - :param sid: The SID of the Sim resource to fetch - :returns: twilio.rest.wireless.v1.sim.SimContext - :rtype: twilio.rest.wireless.v1.sim.SimContext + :returns: True if delete succeeds, False otherwise """ - super(SimContext, self).__init__(version) - # Path Solution - self._solution = {'sid': sid, } - self._uri = '/Sims/{sid}'.format(**self._solution) + headers = values.of({}) - # Dependents - self._usage_records = None - self._data_sessions = None + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) - def fetch(self): + def fetch(self) -> SimInstance: """ Fetch the SimInstance + :returns: The fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance """ - payload = self._version.fetch(method='GET', uri=self._uri, ) - return SimInstance(self._version, payload, sid=self._solution['sid'], ) + headers = values.of({}) - 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, reset_status=values.unset, - account_sid=values.unset): - """ - Update the SimInstance + headers["Accept"] = "application/json" - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode callback_method: The HTTP method we should use to call callback_url - :param unicode callback_url: The URL we should call when the Sim resource has finished updating - :param unicode friendly_name: A string to describe the Sim resource - :param unicode rate_plan: The SID or unique name of the RatePlan resource to which the Sim resource should be assigned - :param SimInstance.Status status: The new status of the Sim resource - :param unicode commands_callback_method: The HTTP method we should use to call commands_callback_url - :param unicode commands_callback_url: The URL we should call when the SIM sends a Command - :param unicode sms_fallback_method: The HTTP method we should use to call sms_fallback_url - :param unicode sms_fallback_url: The URL we should call when an error occurs while retrieving or executing the TwiML requested from sms_url - :param unicode sms_method: The HTTP method we should use to call sms_url - :param unicode sms_url: The URL we should call when the SIM-connected device sends an SMS message that is not a Command - :param unicode voice_fallback_method: The HTTP method we should use to call voice_fallback_url - :param unicode voice_fallback_url: The URL we should call when an error occurs while retrieving or executing the TwiML requested from voice_url - :param unicode voice_method: The HTTP method we should use when we call voice_url - :param unicode voice_url: The URL we should call when the SIM-connected device makes a voice call - :param SimInstance.ResetStatus reset_status: Initiate a connectivity reset on a SIM - :param unicode account_sid: The SID of the Account to which the Sim resource should belong + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - :returns: The 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, - 'ResetStatus': reset_status, - 'AccountSid': account_sid, - }) - - payload = self._version.update(method='POST', uri=self._uri, data=data, ) - - return SimInstance(self._version, payload, sid=self._solution['sid'], ) - - def delete(self): - """ - Deletes the SimInstance + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - :returns: True if delete succeeds, False otherwise - :rtype: bool + async def fetch_async(self) -> SimInstance: """ - return self._version.delete(method='DELETE', uri=self._uri, ) + Asynchronous coroutine to fetch the SimInstance - @property - def usage_records(self): - """ - Access the usage_records - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList + :returns: The fetched SimInstance """ - if self._usage_records is None: - self._usage_records = UsageRecordList(self._version, sim_sid=self._solution['sid'], ) - return self._usage_records - @property - def data_sessions(self): - """ - Access the data_sessions + headers = values.of({}) - :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'], ) - return self._data_sessions + headers["Accept"] = "application/json" - def __repr__(self): - """ - Provide a friendly representation + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) - :returns: Machine friendly representation - :rtype: str + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: """ - context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) - return ''.format(context) + 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). -class SimInstance(InstanceResource): - """ """ + :returns: The updated SimInstance + """ - class Status(object): - NEW = "new" - READY = "ready" - ACTIVE = "active" - SUSPENDED = "suspended" - DEACTIVATED = "deactivated" - CANCELED = "canceled" - SCHEDULED = "scheduled" - UPDATING = "updating" + 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({}) - class ResetStatus(object): - RESETTING = "resetting" + headers["Content-Type"] = "application/x-www-form-urlencoded" - 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.get('sid'), - 'unique_name': payload.get('unique_name'), - 'account_sid': payload.get('account_sid'), - 'rate_plan_sid': payload.get('rate_plan_sid'), - 'friendly_name': payload.get('friendly_name'), - 'iccid': payload.get('iccid'), - 'e_id': payload.get('e_id'), - 'status': payload.get('status'), - 'reset_status': payload.get('reset_status'), - 'commands_callback_url': payload.get('commands_callback_url'), - 'commands_callback_method': payload.get('commands_callback_method'), - 'sms_fallback_method': payload.get('sms_fallback_method'), - 'sms_fallback_url': payload.get('sms_fallback_url'), - 'sms_method': payload.get('sms_method'), - 'sms_url': payload.get('sms_url'), - 'voice_fallback_method': payload.get('voice_fallback_method'), - 'voice_fallback_url': payload.get('voice_fallback_url'), - 'voice_method': payload.get('voice_method'), - 'voice_url': payload.get('voice_url'), - 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), - 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), - 'url': payload.get('url'), - 'links': payload.get('links'), - 'ip_address': payload.get('ip_address'), - } + headers["Accept"] = "application/json" - # Context - self._context = None - self._solution = {'sid': sid or self._properties['sid'], } + payload = self._version.update( + method="POST", uri=self._uri, data=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 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: SimContext for this SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimContext + :returns: The updated SimInstance """ - if self._context is None: - self._context = SimContext(self._version, sid=self._solution['sid'], ) - return self._context - @property - def sid(self): - """ - :returns: The unique string that identifies the Sim resource - :rtype: unicode - """ - return self._properties['sid'] + 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 unique_name(self): - """ - :returns: An application-defined string that uniquely identifies the resource - :rtype: unicode - """ - return self._properties['unique_name'] + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def account_sid(self): - """ - :returns: The SID of the Account to which the Sim resource belongs - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def rate_plan_sid(self): - """ - :returns: The SID of the RatePlan resource to which the Sim resource is assigned. - :rtype: unicode - """ - return self._properties['rate_plan_sid'] + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def friendly_name(self): - """ - :returns: The string that you assigned to describe the Sim resource - :rtype: unicode - """ - return self._properties['friendly_name'] + return SimInstance(self._version, payload, sid=self._solution["sid"]) @property - def iccid(self): + def data_sessions(self) -> DataSessionList: """ - :returns: The ICCID associated with the SIM - :rtype: unicode + Access the data_sessions """ - return self._properties['iccid'] + if self._data_sessions is None: + self._data_sessions = DataSessionList( + self._version, + self._solution["sid"], + ) + return self._data_sessions @property - def e_id(self): + def usage_records(self) -> UsageRecordList: """ - :returns: Deprecated - :rtype: unicode + Access the usage_records """ - return self._properties['e_id'] + if self._usage_records is None: + self._usage_records = UsageRecordList( + self._version, + self._solution["sid"], + ) + return self._usage_records - @property - def status(self): - """ - :returns: The status of the Sim resource - :rtype: SimInstance.Status + def __repr__(self) -> str: """ - return self._properties['status'] + Provide a friendly representation - @property - def reset_status(self): - """ - :returns: The connectivity reset status of the SIM - :rtype: SimInstance.ResetStatus + :returns: Machine friendly representation """ - return self._properties['reset_status'] + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - @property - def commands_callback_url(self): - """ - :returns: The URL we call when the SIM originates a machine-to-machine Command - :rtype: unicode - """ - return self._properties['commands_callback_url'] - @property - def commands_callback_method(self): - """ - :returns: The HTTP method we use to call commands_callback_url - :rtype: unicode - """ - return self._properties['commands_callback_method'] +class SimPage(Page): - @property - def sms_fallback_method(self): - """ - :returns: The HTTP method we use to call sms_fallback_url - :rtype: unicode + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ - return self._properties['sms_fallback_method'] + Build an instance of SimInstance - @property - def sms_fallback_url(self): - """ - :returns: The URL we call when an error occurs while retrieving or executing the TwiML requested from the sms_url - :rtype: unicode + :param payload: Payload response from the API """ - return self._properties['sms_fallback_url'] + return SimInstance(self._version, payload) - @property - def sms_method(self): + def __repr__(self) -> str: """ - :returns: The HTTP method we use to call sms_url - :rtype: unicode - """ - return self._properties['sms_method'] + Provide a friendly representation - @property - def sms_url(self): - """ - :returns: The URL we call when the SIM-connected device sends an SMS message that is not a Command - :rtype: unicode + :returns: Machine friendly representation """ - return self._properties['sms_url'] + return "" - @property - def voice_fallback_method(self): - """ - :returns: The HTTP method we use to call voice_fallback_url - :rtype: unicode - """ - return self._properties['voice_fallback_method'] - @property - def voice_fallback_url(self): - """ - :returns: The URL we call when an error occurs while retrieving or executing the TwiML requested from voice_url - :rtype: unicode - """ - return self._properties['voice_fallback_url'] +class SimList(ListResource): - @property - def voice_method(self): + def __init__(self, version: Version): """ - :returns: The HTTP method we use to call voice_url - :rtype: unicode - """ - return self._properties['voice_method'] + Initialize the SimList - @property - def voice_url(self): - """ - :returns: The URL we call when the SIM-connected device makes a voice call - :rtype: unicode - """ - return self._properties['voice_url'] + :param version: Version that contains the resource - @property - def date_created(self): """ - :returns: The ISO 8601 date and time in GMT when the resource was created - :rtype: datetime - """ - return self._properties['date_created'] + super().__init__(version) - @property - def date_updated(self): - """ - :returns: The ISO 8601 date and time in GMT when the Sim resource was last updated - :rtype: datetime - """ - return self._properties['date_updated'] + self._uri = "/Sims" - @property - def url(self): + 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]: """ - :returns: The absolute URL of the resource - :rtype: unicode + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['url'] + 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 links(self): + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: """ - :returns: The URLs of related subresources - :rtype: unicode + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results """ - return self._properties['links'] + 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 ip_address(self): + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: """ - :returns: Deprecated - :rtype: unicode + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: """ - return self._properties['ip_address'] + Retrieve a single page of SimInstance records from the API. + Request is executed immediately - def fetch(self): + :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 """ - Fetch the SimInstance + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - :returns: The fetched SimInstance - :rtype: twilio.rest.wireless.v1.sim.SimInstance + headers = values.of({"Content-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._proxy.fetch() + 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" - 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, reset_status=values.unset, - account_sid=values.unset): + 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: """ - Update the SimInstance + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately - :param unicode unique_name: An application-defined string that uniquely identifies the resource - :param unicode callback_method: The HTTP method we should use to call callback_url - :param unicode callback_url: The URL we should call when the Sim resource has finished updating - :param unicode friendly_name: A string to describe the Sim resource - :param unicode rate_plan: The SID or unique name of the RatePlan resource to which the Sim resource should be assigned - :param SimInstance.Status status: The new status of the Sim resource - :param unicode commands_callback_method: The HTTP method we should use to call commands_callback_url - :param unicode commands_callback_url: The URL we should call when the SIM sends a Command - :param unicode sms_fallback_method: The HTTP method we should use to call sms_fallback_url - :param unicode sms_fallback_url: The URL we should call when an error occurs while retrieving or executing the TwiML requested from sms_url - :param unicode sms_method: The HTTP method we should use to call sms_url - :param unicode sms_url: The URL we should call when the SIM-connected device sends an SMS message that is not a Command - :param unicode voice_fallback_method: The HTTP method we should use to call voice_fallback_url - :param unicode voice_fallback_url: The URL we should call when an error occurs while retrieving or executing the TwiML requested from voice_url - :param unicode voice_method: The HTTP method we should use when we call voice_url - :param unicode voice_url: The URL we should call when the SIM-connected device makes a voice call - :param SimInstance.ResetStatus reset_status: Initiate a connectivity reset on a SIM - :param unicode account_sid: The SID of the Account to which the Sim resource should belong + :param target_url: API-generated URL for the requested results page - :returns: The 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, - reset_status=reset_status, - account_sid=account_sid, - ) + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) - def delete(self): + async def get_page_async(self, target_url: str) -> SimPage: """ - Deletes the SimInstance + Asynchronously retrieve a specific page of SimInstance 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 SimInstance """ - return self._proxy.delete() + 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 b667ab8c81..b4c50d608d 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -1,348 +1,327 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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): - """ """ - - def __init__(self, version, sim_sid): - """ - Initialize the DataSessionList - - :param Version version: Version that contains the resource - :param sim_sid: The SID of the Sim resource that the Data Session is for - - :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 date that the record ended, given as GMT in ISO 8601 format - :param datetime start: The date that the Data Session started, given as GMT in ISO 8601 format - :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']) +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 date that the record ended, given as GMT in ISO 8601 format - :param datetime start: The date that the Data Session started, given as GMT in ISO 8601 format - :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 date that the record ended, given as GMT in ISO 8601 format - :param datetime start: The date that the Data Session started, given as GMT in ISO 8601 format - :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 """ - data = 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(method='GET', uri=self._uri, params=data, ) - 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, - ) + super().__init__(version) - return DataSessionPage(self._version, response, self._solution) - - 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): - """ """ + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is 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 SID of the Sim resource that the Data Session is for + 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): - """ """ + 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.get('sid'), - 'sim_sid': payload.get('sim_sid'), - 'account_sid': payload.get('account_sid'), - 'radio_link': payload.get('radio_link'), - 'operator_mcc': payload.get('operator_mcc'), - 'operator_mnc': payload.get('operator_mnc'), - 'operator_country': payload.get('operator_country'), - 'operator_name': payload.get('operator_name'), - 'cell_id': payload.get('cell_id'), - 'cell_location_estimate': payload.get('cell_location_estimate'), - 'packets_uploaded': deserialize.integer(payload.get('packets_uploaded')), - 'packets_downloaded': deserialize.integer(payload.get('packets_downloaded')), - 'last_updated': deserialize.iso8601_datetime(payload.get('last_updated')), - 'start': deserialize.iso8601_datetime(payload.get('start')), - 'end': deserialize.iso8601_datetime(payload.get('end')), - 'imei': payload.get('imei'), - } + 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 unique string that identifies the resource - :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 SID of the Sim resource that the Data Session is for - :rtype: unicode - """ - return self._properties['sim_sid'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode - """ - return self._properties['account_sid'] + headers["Accept"] = "application/json" - @property - def radio_link(self): - """ - :returns: The generation of wireless technology that the device was using - :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): - """ - :returns: The 'mobile country code' is the unique ID of the home country where the Data Session took place - :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, + ) -> DataSessionPage: """ - 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 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place - :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 three letter country code representing where the device's Data Session took place - :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 friendly name of the mobile operator network that the SIM-connected device is attached to - :rtype: unicode - """ - return self._properties['operator_name'] + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - @property - def cell_id(self): - """ - :returns: The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated - :rtype: unicode - """ - return self._properties['cell_id'] + headers["Accept"] = "application/json" - @property - def cell_location_estimate(self): - """ - :returns: An object with the estimated location where the device's Data Session took place - :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): + def get_page(self, target_url: str) -> DataSessionPage: """ - :returns: The number of packets uploaded by the device between the start time and when the Data Session was last updated - :rtype: unicode - """ - 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 number of packets downloaded by the device between the start time and when the Data Session was last updated - :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 date that the resource was last updated, given as GMT in ISO 8601 format - :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): + async def get_page_async(self, target_url: str) -> DataSessionPage: """ - :returns: The date that the Data Session started, given as GMT in ISO 8601 format - :rtype: datetime - """ - 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 date that the record ended, given as GMT in ISO 8601 format - :rtype: datetime - """ - return self._properties['end'] + :param target_url: API-generated URL for the requested results page - @property - def imei(self): - """ - :returns: The unique ID of the device using the SIM to connect - :rtype: unicode + :returns: Page of DataSessionInstance """ - return self._properties['imei'] + 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 d481423b73..1cd26b6c2e 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -1,264 +1,353 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 UsageRecordList(ListResource): - """ """ +class UsageRecordInstance(InstanceResource): - def __init__(self, version, sim_sid): - """ - Initialize the UsageRecordList + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" - :param Version version: Version that contains the resource - :param sim_sid: The SID of the Sim resource that this Usage Record is for + """ + :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, + } - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordList + def __repr__(self) -> str: """ - super(UsageRecordList, self).__init__(version) - - # Path Solution - self._solution = {'sim_sid': sim_sid, } - self._uri = '/Sims/{sim_sid}/UsageRecords'.format(**self._solution) + Provide a friendly representation - def stream(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + :returns: Machine friendly representation """ - 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. + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) - :param datetime end: Only include usage that occurred on or before this date - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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.wireless.v1.sim.usage_record.UsageRecordInstance] +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: """ - limits = self._version.read_limits(limit, page_size) + Build an instance of UsageRecordInstance - page = self.page(end=end, start=start, granularity=granularity, page_size=limits['page_size'], ) + :param payload: Payload response from the API + """ + return UsageRecordInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) - return self._version.stream(page, limits['limit']) + def __repr__(self) -> str: + """ + Provide a friendly representation - def list(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + :returns: Machine friendly representation """ - Lists UsageRecordInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. + return "" - :param datetime end: Only include usage that occurred on or before this date - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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.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): +class UsageRecordList(ListResource): + + def __init__(self, version: Version, sim_sid: str): """ - Retrieve a single page of UsageRecordInstance records from the API. - Request is executed immediately + Initialize the UsageRecordList - :param datetime end: Only include usage that occurred on or before this date - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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 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: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage """ - data = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'Granularity': granularity, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) - - response = self._version.page(method='GET', uri=self._uri, params=data, ) + super().__init__(version) - return UsageRecordPage(self._version, response, self._solution) + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/UsageRecords".format(**self._solution) - def get_page(self, target_url): + 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]: """ - Retrieve a specific page of UsageRecordInstance records from the API. - Request is executed immediately + 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 target_url: API-generated URL for the requested results page + :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: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + :returns: Generator that will yield up to limit results """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] ) - return UsageRecordPage(self._version, response, self._solution) + return self._version.stream(page, limits["limit"]) - def __repr__(self): + 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]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str - """ - return '' + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) -class UsageRecordPage(Page): - """ """ + return self._version.stream_async(page, limits["limit"]) - def __init__(self, version, response, solution): + 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]: """ - Initialize the UsageRecordPage + 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 Version version: Version that contains the resource - :param Response response: Response from the API - :param sim_sid: The SID of the Sim resource that this Usage Record is for + :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, + ) + ) - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordPage + 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]: """ - super(UsageRecordPage, self).__init__(version, response) - - # Path Solution - self._solution = solution + 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_instance(self, payload): + :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: """ - Build an instance of UsageRecordInstance + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately - :param dict payload: Payload response from the API + :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: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance + :returns: Page of UsageRecordInstance """ - return UsageRecordInstance(self._version, payload, sim_sid=self._solution['sim_sid'], ) + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) - def __repr__(self): - """ - Provide a friendly representation + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: Machine friendly representation - :rtype: str - """ - return '' + headers["Accept"] = "application/json" + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) -class UsageRecordInstance(InstanceResource): - """ """ + 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 - class Granularity(object): - HOURLY = "hourly" - DAILY = "daily" - ALL = "all" + :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 - def __init__(self, version, payload, sim_sid): + :returns: Page of UsageRecordInstance """ - Initialize the 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, + } + ) - :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance - """ - super(UsageRecordInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'sim_sid': payload.get('sim_sid'), - 'account_sid': payload.get('account_sid'), - 'period': payload.get('period'), - 'commands': payload.get('commands'), - 'data': payload.get('data'), - } + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - # Context - self._context = None - self._solution = {'sim_sid': sim_sid, } + headers["Accept"] = "application/json" - @property - def sim_sid(self): - """ - :returns: The SID of the Sim resource that this Usage Record is for - :rtype: unicode - """ - return self._properties['sim_sid'] + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :rtype: unicode + def get_page(self, target_url: str) -> UsageRecordPage: """ - return self._properties['account_sid'] + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - @property - def period(self): - """ - :returns: The time period for which the usage is reported - :rtype: dict - """ - return self._properties['period'] + :param target_url: API-generated URL for the requested results page - @property - def commands(self): - """ - :returns: An object that describes the SIM's usage of Commands during the specified period - :rtype: dict + :returns: Page of UsageRecordInstance """ - return self._properties['commands'] + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) - @property - def data(self): + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - :returns: An object that describes the SIM's data usage during the specified period - :rtype: dict + 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 """ - 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 index 8cdab8cae8..07135cf98b 100644 --- a/twilio/rest/wireless/v1/usage_record.py +++ b/twilio/rest/wireless/v1/usage_record.py @@ -1,253 +1,340 @@ -# coding=utf-8 r""" -This code was generated by -\ / _ _ _| _ _ - | (_)\/(_)(_|\/| |(/_ v1.0.0 - / / + 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 UsageRecordList(ListResource): - """ """ +class UsageRecordInstance(InstanceResource): - def __init__(self, version): - """ - Initialize the UsageRecordList + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" - :param Version version: Version that contains the resource + """ + :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). + """ - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordList - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordList - """ - super(UsageRecordList, self).__init__(version) + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) - # Path Solution - self._solution = {} - self._uri = '/UsageRecords'.format(**self._solution) + 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 stream(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + def __repr__(self) -> str: """ - 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 - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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.usage_record.UsageRecordInstance] + :returns: Machine friendly representation """ - limits = self._version.read_limits(limit, page_size) - page = self.page(end=end, start=start, granularity=granularity, page_size=limits['page_size'], ) + return "" + - return self._version.stream(page, limits['limit']) +class UsageRecordPage(Page): - def list(self, end=values.unset, start=values.unset, granularity=values.unset, - limit=None, page_size=None): + def get_instance(self, payload: Dict[str, Any]) -> 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. + Build an instance of UsageRecordInstance - :param datetime end: Only include usage that has occurred on or before this date - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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 payload: Payload response from the API + """ + return UsageRecordInstance(self._version, payload) - :returns: Generator that will yield up to limit results - :rtype: list[twilio.rest.wireless.v1.usage_record.UsageRecordInstance] + def __repr__(self) -> str: """ - return list(self.stream( - end=end, - start=start, - granularity=granularity, - limit=limit, - page_size=page_size, - )) + Provide a friendly representation - def page(self, end=values.unset, start=values.unset, granularity=values.unset, - page_token=values.unset, page_number=values.unset, - page_size=values.unset): + :returns: Machine friendly representation """ - Retrieve a single page of UsageRecordInstance records from the API. - Request is executed immediately + return "" - :param datetime end: Only include usage that has occurred on or before this date - :param datetime start: Only include usage that has occurred on or after this date - :param UsageRecordInstance.Granularity granularity: The time-based grouping that results are aggregated by - :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 UsageRecordInstance - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordPage - """ - data = values.of({ - 'End': serialize.iso8601_datetime(end), - 'Start': serialize.iso8601_datetime(start), - 'Granularity': granularity, - 'PageToken': page_token, - 'Page': page_number, - 'PageSize': page_size, - }) +class UsageRecordList(ListResource): - response = self._version.page(method='GET', uri=self._uri, params=data, ) + def __init__(self, version: Version): + """ + Initialize the UsageRecordList - return UsageRecordPage(self._version, response, self._solution) + :param version: Version that contains the resource - def get_page(self, target_url): """ - Retrieve a specific page of UsageRecordInstance records from the API. - Request is executed immediately + 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 str target_url: API-generated URL for the requested results page + :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: Page of UsageRecordInstance - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordPage + :returns: Generator that will yield up to limit results """ - response = self._version.domain.twilio.request( - 'GET', - target_url, + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] ) - return UsageRecordPage(self._version, response, self._solution) + return self._version.stream(page, limits["limit"]) - def __repr__(self): + 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]: """ - Provide a friendly representation + 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. - :returns: Machine friendly representation - :rtype: str + :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 """ - return '' + 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"]) -class UsageRecordPage(Page): - """ """ + 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. - def __init__(self, version, response, solution): + :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 """ - Initialize the UsageRecordPage + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) - :param Version version: Version that contains the resource - :param Response response: Response from the API + 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. - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordPage - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordPage + :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 """ - super(UsageRecordPage, self).__init__(version, response) + 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 - # Path Solution - self._solution = solution + :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 - def get_instance(self, payload): + :returns: Page of UsageRecordInstance """ - Build an instance 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, + } + ) - :param dict payload: Payload response from the API + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordInstance - """ - return UsageRecordInstance(self._version, payload, ) + headers["Accept"] = "application/json" - def __repr__(self): + 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: """ - Provide a friendly representation + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately - :returns: Machine friendly representation - :rtype: str - """ - return '' + :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, + } + ) -class UsageRecordInstance(InstanceResource): - """ """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - class Granularity(object): - HOURLY = "hourly" - DAILY = "daily" - ALL = "all" + headers["Accept"] = "application/json" - def __init__(self, version, payload): - """ - Initialize the UsageRecordInstance + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) - :returns: twilio.rest.wireless.v1.usage_record.UsageRecordInstance - :rtype: twilio.rest.wireless.v1.usage_record.UsageRecordInstance + def get_page(self, target_url: str) -> UsageRecordPage: """ - super(UsageRecordInstance, self).__init__(version) - - # Marshaled Properties - self._properties = { - 'account_sid': payload.get('account_sid'), - 'period': payload.get('period'), - 'commands': payload.get('commands'), - 'data': payload.get('data'), - } + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately - # Context - self._context = None - self._solution = {} + :param target_url: API-generated URL for the requested results page - @property - def account_sid(self): - """ - :returns: The SID of the Account that created the resource - :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) - @property - def period(self): + async def get_page_async(self, target_url: str) -> UsageRecordPage: """ - :returns: The time period for which usage is reported - :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: An object that describes the aggregated Commands usage for all SIMs during the specified period - :rtype: dict - """ - return self._properties['commands'] + :param target_url: API-generated URL for the requested results page - @property - def data(self): - """ - :returns: An object that describes the aggregated Data usage for all SIMs over the period - :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) - def __repr__(self): + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation - :rtype: str """ - return '' + return "" diff --git a/twilio/twiml/__init__.py b/twilio/twiml/__init__.py index 44e6fa0319..70a4df8309 100644 --- a/twilio/twiml/__init__.py +++ b/twilio/twiml/__init__.py @@ -4,10 +4,10 @@ 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:] @@ -20,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): @@ -32,11 +32,11 @@ class TwiMLException(Exception): class TwiML(object): MAP = { - 'from_': 'from', - 'xml_lang': 'xml:lang', - 'interpret_as': 'interpret-as', - 'for_': 'for', - 'break_': 'break' + "from_": "from", + "xml_lang": "xml:lang", + "interpret_as": "interpret-as", + "for_": "for", + "break_": "break", } def __init__(self, **kwargs): @@ -64,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): """ @@ -87,7 +91,7 @@ def nest(self, verb): :returns: the TwiML verb """ if not isinstance(verb, TwiML) and not isinstance(verb, str): - raise TwiMLException('Only nesting of TwiML and strings are allowed') + raise TwiMLException("Only nesting of TwiML and strings are allowed") self.verbs.append(verb) return verb diff --git a/twilio/twiml/fax_response.py b/twilio/twiml/fax_response.py index 00303b59b6..89233bd407 100644 --- a/twilio/twiml/fax_response.py +++ b/twilio/twiml/fax_response.py @@ -6,22 +6,27 @@ / / """ -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, media_type=None, page_size=None, - store_media=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 @@ -34,19 +39,21 @@ def receive(self, action=None, method=None, media_type=None, page_size=None, :returns: element """ - return self.nest(Receive( - action=action, - method=method, - media_type=media_type, - page_size=page_size, - store_media=store_media, - **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 9288866477..ec36c74c06 100644 --- a/twilio/twiml/messaging_response.py +++ b/twilio/twiml/messaging_response.py @@ -6,44 +6,52 @@ / / """ -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 d06387e5ca..18078b90a3 100644 --- a/twilio/twiml/voice_response.py +++ b/twilio/twiml/voice_response.py @@ -6,20 +6,17 @@ / / """ -import json -from twilio.base.obsolete import deprecated_method 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): """ @@ -33,12 +30,29 @@ def connect(self, action=None, method=None, **kwargs): """ 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, **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 @@ -56,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): """ @@ -88,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 @@ -103,22 +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, debug=None, action_on_empty_result=None, - speech_model=None, enhanced=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 @@ -144,27 +199,29 @@ def gather(self, input=None, action=None, method=None, timeout=None, :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, - debug=debug, - action_on_empty_result=action_on_empty_result, - speech_model=speech_model, - enhanced=enhanced, - **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): """ @@ -210,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 @@ -224,21 +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, - recording_status_callback_event=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 @@ -258,21 +334,23 @@ def record(self, action=None, method=None, timeout=None, finish_on_key=None, :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, - recording_status_callback_event=recording_status_callback_event, - 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): """ @@ -304,15 +382,25 @@ def say(self, message=None, voice=None, loop=None, language=None, **kwargs): :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=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 @@ -326,22 +414,40 @@ 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 - )) - - 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): + 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 @@ -367,30 +473,39 @@ def pay(self, input=None, action=None, bank_account_type=None, :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, - **kwargs): + 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 @@ -398,17 +513,21 @@ def prompt(self, for_=None, error_type=None, card_type=None, attempt=None, :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, - **kwargs - )) + 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): """ @@ -446,11 +565,11 @@ def refer(self, action=None, method=None, **kwargs): class Refer(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Refer, self).__init__(**kwargs) - self.name = 'Refer' + self.name = "Refer" def sip(self, sip_url, **kwargs): """ @@ -463,37 +582,33 @@ def sip(self, sip_url, **kwargs): """ return self.nest(ReferSip(sip_url, **kwargs)) - @deprecated_method('sip') - def refer_sip(self, sip_url, **kwargs): - """ - Create a element - - :param sip_url: SIP URL - :param kwargs: additional attributes - - :returns: element - """ - return self.sip(sip_url, **kwargs) - class ReferSip(TwiML): - """ TwiML Noun used in """ + """ TwiML Noun used in """ def __init__(self, sip_url, **kwargs): super(ReferSip, self).__init__(**kwargs) - self.name = 'Sip' + self.name = "Sip" self.value = sip_url class Stop(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Stop, self).__init__(**kwargs) - self.name = 'Stop' - - def stream(self, name=None, connector_name=None, url=None, track=None, - **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 @@ -501,32 +616,134 @@ def stream(self, name=None, connector_name=None, url=None, track=None, :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, **kwargs)) - - def siprec(self, name=None, connector_name=None, track=None, **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, **kwargs)) + 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""" + def __init__(self, **kwargs): + super(Transcription, self).__init__(**kwargs) + self.name = "Transcription" -class Siprec(TwiML): - """ TwiML Noun """ + def config(self, name=None, value=None, **kwargs): + """ + Create a element - def __init__(self, **kwargs): - super(Siprec, self).__init__(**kwargs) - self.name = 'Siprec' + :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): """ @@ -542,19 +759,47 @@ def parameter(self, name=None, value=None, **kwargs): class Parameter(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, **kwargs): super(Parameter, self).__init__(**kwargs) - self.name = 'Parameter' + self.name = "Parameter" + + +class Config(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Config, self).__init__(**kwargs) + self.name = "Config" + + +class Siprec(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + 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 Stream(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, **kwargs): super(Stream, self).__init__(**kwargs) - self.name = 'Stream' + self.name = "Stream" def parameter(self, name=None, value=None, **kwargs): """ @@ -570,14 +815,22 @@ def parameter(self, name=None, value=None, **kwargs): class Start(TwiML): - """ TwiML Verb """ + """ 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, - **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 @@ -585,32 +838,122 @@ def stream(self, name=None, connector_name=None, url=None, track=None, :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, **kwargs)) - - def siprec(self, name=None, connector_name=None, track=None, **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, **kwargs)) + 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 """ + """ Twiml Verb""" def __init__(self, **kwargs): super(Prompt, self).__init__(**kwargs) - self.name = 'Prompt' + self.name = "Prompt" def say(self, message=None, voice=None, loop=None, language=None, **kwargs): """ @@ -619,12 +962,14 @@ def say(self, message=None, voice=None, loop=None, language=None, **kwargs): :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=message, voice=voice, loop=loop, language=language, **kwargs)) + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) def play(self, url=None, loop=None, digits=None, **kwargs): """ @@ -652,29 +997,29 @@ def pause(self, length=None, **kwargs): class Pause(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Pause, self).__init__(**kwargs) - self.name = 'Pause' + self.name = "Pause" class Play(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, url=None, **kwargs): super(Play, self).__init__(**kwargs) - self.name = 'Play' + self.name = "Play" if url: self.value = url class Say(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, message=None, **kwargs): super(Say, self).__init__(**kwargs) - self.name = 'Say' + self.name = "Say" if message: self.value = message @@ -690,8 +1035,131 @@ def break_(self, strength=None, time=None, **kwargs): """ return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) - @deprecated_method('break_') - def ssml_break(self, strength=None, time=None, **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 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 @@ -701,9 +1169,9 @@ def ssml_break(self, strength=None, time=None, **kwargs): :returns: element """ - return self.break_(strength=strength, time=time, **kwargs) + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) - def emphasis(self, words, level=None, **kwargs): + def emphasis(self, words=None, level=None, **kwargs): """ Create a element @@ -713,59 +1181,129 @@ def emphasis(self, words, level=None, **kwargs): :returns: element """ - return self.nest(SsmlEmphasis(words, level=level, **kwargs)) + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) - @deprecated_method('emphasis') - def ssml_emphasis(self, words, level=None, **kwargs): + def phoneme(self, words, alphabet=None, ph=None, **kwargs): """ - Create a element + Create a element - :param words: Words to emphasize - :param level: Specify the degree of emphasis + :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.emphasis(words, level=level, **kwargs) + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) - def lang(self, words, xml_lang=None, **kwargs): + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): """ - Create a element + Create a element :param words: Words to speak - :param xml:lang: Specify the language + :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(SsmlLang(words, xml_lang=xml_lang, **kwargs)) + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) - @deprecated_method('lang') - def ssml_lang(self, words, xml_lang=None, **kwargs): + def say_as(self, words, interpret_as=None, format=None, **kwargs): """ - Create a element + Create a element - :param words: Words to speak - :param xml:lang: Specify the language + :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 + :returns: element """ - return self.lang(words, xml_lang=xml_lang, **kwargs) + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) - def p(self, words, **kwargs): + def sub(self, words, alias=None, **kwargs): """ - Create a

    element + 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 + :returns: element """ - return self.nest(SsmlP(words, **kwargs)) + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) - @deprecated_method('p') - def ssml_p(self, words, **kwargs): + def p(self, words=None, **kwargs): """ Create a

    element @@ -774,7 +1312,7 @@ def ssml_p(self, words, **kwargs): :returns:

    element """ - return self.p(words, **kwargs) + return self.nest(SsmlP(words=words, **kwargs)) def phoneme(self, words, alphabet=None, ph=None, **kwargs): """ @@ -789,98 +1327,545 @@ def phoneme(self, words, alphabet=None, ph=None, **kwargs): """ return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) - @deprecated_method('phoneme') - def ssml_phoneme(self, words, alphabet=None, ph=None, **kwargs): + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): """ - Create a element + Create a element :param words: Words to speak - :param alphabet: Specify the phonetic alphabet - :param ph: Specifiy the phonetic symbols for pronunciation + :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( + 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): """ - return self.phoneme(words, alphabet=alphabet, ph=ph, **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 prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): + def break_(self, strength=None, time=None, **kwargs): """ - Create a element + 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 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(SsmlProsody(words, volume=volume, rate=rate, pitch=pitch, **kwargs)) + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) - @deprecated_method('prosody') - def ssml_prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): + def emphasis(self, words=None, level=None, **kwargs): """ - Create a element + 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 words: Words to emphasize + :param level: Specify the degree of emphasis :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.prosody(words, volume=volume, rate=rate, pitch=pitch, **kwargs) + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) - def s(self, words, **kwargs): + def lang(self, words=None, xml_lang=None, **kwargs): """ - Create a element + Create a element :param words: Words to speak + :param xml:lang: Specify the language :param kwargs: additional attributes - :returns: element + :returns: element """ - return self.nest(SsmlS(words, **kwargs)) + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) - @deprecated_method('s') - def ssml_s(self, words, **kwargs): + def phoneme(self, words, alphabet=None, ph=None, **kwargs): """ - Create a element + 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 + :returns: element """ - return self.s(words, **kwargs) + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) - def say_as(self, words, interpret_as=None, role=None, **kwargs): + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): """ - Create a element + Create a element - :param words: Words to be interpreted - :param interpret-as: Specify the type of words are spoken - :param role: Specify the format of the date when interpret-as is set to date + :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(SsmlSayAs(words, interpret_as=interpret_as, role=role, **kwargs)) + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) - @deprecated_method('say_as') - def ssml_say_as(self, words, interpret_as=None, role=None, **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 role: Specify the format of the date when interpret-as is set to date + :param format: Specify the format of the date when interpret-as is set to date :param kwargs: additional attributes :returns: element """ - return self.say_as(words, interpret_as=interpret_as, role=role, **kwargs) + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) def sub(self, words, alias=None, **kwargs): """ @@ -894,33 +1879,7 @@ def sub(self, words, alias=None, **kwargs): """ return self.nest(SsmlSub(words, alias=alias, **kwargs)) - @deprecated_method('sub') - def ssml_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.sub(words, alias=alias, **kwargs) - - def w(self, words, 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, role=role, **kwargs)) - - @deprecated_method('w') - def ssml_w(self, words, role=None, **kwargs): + def w(self, words=None, role=None, **kwargs): """ Create a element @@ -930,107 +1889,33 @@ def ssml_w(self, words, role=None, **kwargs): :returns: element """ - return self.w(words, role=role, **kwargs) - - -class SsmlW(TwiML): - """ Improving Pronunciation by Specifying Parts of Speech in """ - - def __init__(self, words, **kwargs): - super(SsmlW, self).__init__(**kwargs) - self.name = 'w' - self.value = words - - -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 SsmlS(TwiML): - """ Adding A Pause Between Sentences in """ - - def __init__(self, words, **kwargs): - super(SsmlS, self).__init__(**kwargs) - self.name = 's' - self.value = words - - -class SsmlProsody(TwiML): - """ Controling Volume, Speaking Rate, and Pitch in """ - - def __init__(self, words, **kwargs): - super(SsmlProsody, self).__init__(**kwargs) - self.name = 'prosody' - self.value = words - - -class SsmlPhoneme(TwiML): - """ Using Phonetic Pronunciation in """ - - def __init__(self, words, **kwargs): - super(SsmlPhoneme, self).__init__(**kwargs) - self.name = 'phoneme' - self.value = words - - -class SsmlP(TwiML): - """ Adding a Pause Between Paragraphs in """ - - def __init__(self, words, **kwargs): - super(SsmlP, self).__init__(**kwargs) - self.name = 'p' - self.value = words - - -class SsmlLang(TwiML): - """ Specifying Another Language for Specific Words in """ - - def __init__(self, words, **kwargs): - super(SsmlLang, self).__init__(**kwargs) - self.name = 'lang' - self.value = words - - -class SsmlEmphasis(TwiML): - """ Emphasizing Words in """ - - def __init__(self, words, **kwargs): - super(SsmlEmphasis, self).__init__(**kwargs) - self.name = 'emphasis' - self.value = words + return self.nest(SsmlW(words=words, role=role, **kwargs)) class SsmlBreak(TwiML): - """ Adding a Pause in """ + """Adding a Pause in """ def __init__(self, **kwargs): super(SsmlBreak, self).__init__(**kwargs) - self.name = 'break' + self.name = "break" class Pay(TwiML): - """ Twiml Verb """ + """ 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, - **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 @@ -1038,17 +1923,21 @@ def prompt(self, for_=None, error_type=None, card_type=None, attempt=None, :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, - **kwargs - )) + 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): """ @@ -1064,70 +1953,94 @@ def parameter(self, name=None, value=None, **kwargs): class Sms(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, message, **kwargs): super(Sms, self).__init__(**kwargs) - self.name = 'Sms' + self.name = "Sms" self.value = message class Reject(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Reject, self).__init__(**kwargs) - self.name = 'Reject' + 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 """ + """ TwiML Verb""" def __init__(self, url, **kwargs): super(Redirect, self).__init__(**kwargs) - self.name = 'Redirect' + self.name = "Redirect" self.value = url class Record(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Record, self).__init__(**kwargs) - self.name = 'Record' + self.name = "Record" class Queue(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, name, **kwargs): super(Queue, self).__init__(**kwargs) - self.name = 'Queue' + self.name = "Queue" self.value = name class Leave(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Leave, self).__init__(**kwargs) - self.name = 'Leave' + self.name = "Leave" class Hangup(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Hangup, self).__init__(**kwargs) - self.name = 'Hangup' + 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 """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Gather, self).__init__(**kwargs) - self.name = 'Gather' + self.name = "Gather" def say(self, message=None, voice=None, loop=None, language=None, **kwargs): """ @@ -1136,12 +2049,14 @@ def say(self, message=None, voice=None, loop=None, language=None, **kwargs): :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=message, voice=voice, loop=loop, language=language, **kwargs)) + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) def pause(self, length=None, **kwargs): """ @@ -1169,11 +2084,11 @@ def play(self, url=None, loop=None, digits=None, **kwargs): class Enqueue(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, name=None, **kwargs): super(Enqueue, self).__init__(**kwargs) - self.name = 'Enqueue' + self.name = "Enqueue" if name: self.value = name @@ -1192,34 +2107,41 @@ def task(self, body, priority=None, timeout=None, **kwargs): class Task(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, body, **kwargs): super(Task, self).__init__(**kwargs) - self.name = 'Task' + self.name = "Task" self.value = body class Echo(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Echo, self).__init__(**kwargs) - self.name = 'Echo' + self.name = "Echo" class Dial(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, number=None, **kwargs): super(Dial, self).__init__(**kwargs) - self.name = 'Dial' + 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): + def client( + self, + identity=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): """ Create a element @@ -1233,25 +2155,43 @@ def client(self, identity=None, url=None, method=None, :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, - **kwargs): + 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 @@ -1274,36 +2214,58 @@ def conference(self, name, muted=None, beep=None, :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, - **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, **kwargs): + 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 @@ -1315,24 +2277,47 @@ def number(self, phone_number, send_digits=None, url=None, method=None, :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, - **kwargs - )) - - def queue(self, name, url=None, method=None, reservation_sid=None, - post_work_activity_sid=None, **kwargs): + 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 @@ -1345,14 +2330,16 @@ 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 - )) + 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): """ @@ -1365,9 +2352,25 @@ def sim(self, sim_sid, **kwargs): """ 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, **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 @@ -1379,65 +2382,164 @@ def sip(self, sip_url, username=None, password=None, url=None, method=None, :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, - **kwargs - )) + 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 """ + """ 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, identity=None, **kwargs): super(Client, self).__init__(**kwargs) - self.name = 'Client' + self.name = "Client" if identity: self.value = identity @@ -1466,20 +2568,20 @@ def parameter(self, name=None, value=None, **kwargs): class Identity(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, client_identity, **kwargs): super(Identity, self).__init__(**kwargs) - self.name = 'Identity' + self.name = "Identity" self.value = client_identity class Connect(TwiML): - """ TwiML Verb """ + """ TwiML Verb""" def __init__(self, **kwargs): super(Connect, self).__init__(**kwargs) - self.name = 'Connect' + self.name = "Connect" def room(self, name, participant_identity=None, **kwargs): """ @@ -1491,7 +2593,9 @@ def room(self, name, participant_identity=None, **kwargs): :returns: element """ - return self.nest(Room(name, participant_identity=participant_identity, **kwargs)) + return self.nest( + Room(name, participant_identity=participant_identity, **kwargs) + ) def autopilot(self, name, **kwargs): """ @@ -1504,8 +2608,16 @@ def autopilot(self, name, **kwargs): """ return self.nest(Autopilot(name, **kwargs)) - def stream(self, name=None, connector_name=None, url=None, track=None, - **kwargs): + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): """ Create a element @@ -1513,26 +2625,441 @@ def stream(self, name=None, connector_name=None, url=None, track=None, :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, **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 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 """ + """ TwiML Noun""" def __init__(self, name, **kwargs): super(Autopilot, self).__init__(**kwargs) - self.name = 'Autopilot' + self.name = "Autopilot" self.value = name class Room(TwiML): - """ TwiML Noun """ + """ TwiML Noun""" def __init__(self, name, **kwargs): super(Room, self).__init__(**kwargs) - self.name = 'Room' + self.name = "Room" self.value = name